ajax 跨域问题两种方式

前端之家收集整理的这篇文章主要介绍了ajax 跨域问题两种方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

第一种

$.ajax({
type: "POST",
url : "http://localhost:8088/Shopping/user/ajaxCross.action",
data:"null",
async: false,
dataType:"jsonp",
error: function(request) {
alert("test error");
},
success: function(data) {
alert("success");
alert(data);
$.each(data,function(date){
alert(date);
});
}
});

注意:dataType 一定要为 jsonp 它的格式为 (json格式) 相当于用括号将json格式的数据包含。

_jqjsp({"address":"","birthday":{"date":14,"day":2,"hours":12,"minutes":12,"month":2,"nanos":0,"seconds":12,"time":1489464732000,"timezoneOffset":-480,"year":117},"dentityCode":"1","emaill":"","id":3,"name":"","order":2147483647,"picPath":"","remarks":"","sex":"???","status":1,"trueName":"????4"})


第二种 通过 jquery-jsonp 插件来进行跨域

var url="http://localhost:8088/Shopping/user/ajaxCross.action"  +"?callback=?&id=fdfd";
$.jsonp({
  "url": url,"success": function(data) {
        alert("success");
          alert(data);
           $.each(data,function(date){
                          alert(date);
                      });
  },"error": function(d,msg) {
    alert("Could not find user ");
  }
});

注意:callback=? 这部分一定要写 jquery 默认会添加 如:
http://localhost:8088/Shopping/user/ajaxCross.action?callback=_jqjsp&_1495533338619=

后台代码都是一样的 如:

@ResponseBody @RequestMapping("/ajaxCross") public String ajaxCross(HttpServletRequest request){ String callback = request.getParameter("callback"); User user = userService.findUserById(3); JSONObject jsonStu = JSONObject.fromObject(user); return callback+"("+jsonStu+")"; }

猜你在找的Ajax相关文章