ajax cross domain request problem

Don't talk much, look at the front desk first

$.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");
			}

		})

Here jsonp and jsonCallback parameters jquery documentation gives this explanation



  Simply put, if you use

{

jsonp:"callback_param",

jsonCallback:"callback_fun",

}

It is equivalent to requesting xxx.do?callback_param=callback_fun

 

 

 

Then look at the background:

@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();
				}
			}
		}

	}

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325340738&siteId=291194637