ajax跨域请求问题

不多说话首先看前台

$.ajax({
			url : "http://192.168.1.57:8080/TestM/testAndroid.do",
			type : "get",
			dataType : 'jsonp',  
			jsonp : "callbackParam",
			jsonpCallback: "success_jsonCallback",
			//dateType : "json",
			success : function(data){
				//console.log(data);
				for(var i in data){
					$("#userListRow").append("<li>"+data[i].name +" " +data[i].age +" " +data[i].email +"</li>");
				}
				$("#testdiv").html("aabb");
			},
			error : function(){
				console.log("error");
			}

		})

这里jsonp 和jsonCallback参数jquery文档给出的是这个解释


ajax跨域请求问题
  简单来说如果使用了

{

jsonp:"callback_param",

jsonCallback:"callback_fun",

}

就相当于请求 xxx.do?callback_param=callback_fun

接着来看后台:

@RequestMapping("testAndroid")
	@ResponseBody
	public void testAndroid(String callbackParam, HttpServletResponse response) throws JsonProcessingException {
		response.setCharacterEncoding("UTF-8");
		
		List<Map<String, Object>> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			Map<String, Object> map = new HashMap<>();
			map.put("name", "张三" + i);
			map.put("age", i + 1);
			map.put("email", "email" + i);
			list.add(map);
		}

		ObjectMapper objectmap = new ObjectMapper();
		String json = objectmap.writeValueAsString(list);
		PrintWriter pWriter = null;
		if(StringUtils.isNotBlank(callbackParam)){ // jsonp
			response.setHeader("Content-type", "application/jsonp;charset=UTF-8");
			try {
				pWriter = response.getWriter();
				String result = new String(json.toString().getBytes(), "UTF-8");
				pWriter.write(callbackParam+"(" + result + ")");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (pWriter != null) {
					pWriter.flush();
					pWriter.close();
				}
			}
		}else{ //json
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			try {
				pWriter = response.getWriter();
				String result = new String(json.toString().getBytes(), "utf-8");
				pWriter.write( result);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (pWriter != null) {
					pWriter.flush();
					pWriter.close();
				}
			}
		}

	}

相关推荐