ajax 跨域

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

解决方式一、

js代码

$(document).ready(function(){
   var url='http://localhost:8080/WorkGroupManagment/open/getGroupById"
       +"?id=1&callback=?';
   $.ajax({
     url:url,dataType:'jsonp',processData: false,type:'get',success:function(data){
       alert(data.name);
     },error:function(XMLHttpRequest,textStatus,errorThrown) {
       alert(XMLHttpRequest.status);
       alert(XMLHttpRequest.readyState);
       alert(textStatus);
      }});
   });


后台java代码: @H_502_9@@RequestMapping(value = "/getGroupById") public String getGroupById(@RequestParam("id") Long id,HttpServletRequest request,HttpServletResponse response) throws IOException { String callback = request.getParameter("callback"); ReturnObject result = null; Group group = null; try { group = groupService.getGroupById(id); result = new ReturnObject(group,"获取成功",Constants.RESULT_SUCCESS); } catch (BusinessException e) { e.printStackTrace(); result = new ReturnObject(group,"获取失败",Constants.RESULT_Failed); } String json = JsonConverter.bean2Json(result); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(callback + "(" + json + ")"); return null; }

解决方式二、

使用jsonp

var url="http://localhost:8080/WorkGroupManagment/open/getGroupById"
    +"?id=1&callback=?";
$.jsonp({
  "url": url,"success": function(data) {
     alert(data.result.name);

  },"error": function(d,msg) {

    alert("Could not find user "+msg);  }});
原文链接:https://www.f2er.com/ajax/161440.html

猜你在找的Ajax相关文章