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文档给出的是这个解释
简单来说如果使用了
{
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(); } } } }
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05