jsonp realizes cross-domain access

How to solve the ajax cross-domain problem (transfer)

 

Since I rarely wrote front-end code before (haha, unqualified programmers), json is used in recent projects as a means of interaction between systems, naturally accompanied by many ajax requests, followed by ajax solutions cross-domain issues. This article will describe the whole process of a novice from encountering a cross-domain problem and not knowing it is a cross-domain problem, to knowing that it is a cross-domain problem and not knowing how to solve it, to solving the cross-domain problem, and finally finding two ways to solve the ajax cross-domain problem. .

I don't know if it's a cross domain issue

The reason is this. In order to reuse and reduce repeated development, a user rights management system is developed separately, and other systems obtain authentication and authorization information, which is called system A for the time being; call system A to take B as an example. Using ajax to call the interface of system A in system B (the data format is json), I was very confused at that time. Accessing the corresponding url in system A can return json data normally, but using ajax in system B to request the same url is a little bit confusing. There was no reaction, as if nothing had happened. This has been repeated and changed for a long time, but it has not been solved for a long time, so I asked my colleagues for help and reminded that it might be a cross-domain problem with ajax, so I solved this problem as a cross-domain problem.

Knowing cross-domain but not knowing how to solve it

Knowing the exact cause of the problem, all that remains is to find a solution to the problem. After google for a long time, once again, under the guidance of my colleagues, I know that jQuery's ajax has attributes such as jsonp, which can be used to solve cross-domain problems.

find a solution

Now that we know how to solve the cross-domain problem, the rest is the implementation details. Errors in the implementation process are unavoidable. Because I didn't understand the difference between the json and jsonp formats, I also made mistakes, which took a long time to solve.

First, let's take a look at a simple version of how to use jQuery's ajax to solve cross-domain problems in the page:

copy code
$(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);
     }});
   });
copy code

There is absolutely no problem in writing this way. At first, the error processing function is only alert("error"). In order to further clarify what caused the error, the processing function is changed to the above implementation method. The last line of alert is used as; parsererror. I was puzzled, continued to google, and finally found the answer in the omnipotent stackoverflow, the link is here . The reason is that the format of jsonp is slightly different from that of json, so the code on the server side is slightly different.

Compare the difference between json and jsonp formats:

json format:
{
    "message":"获取成功",
    "state":"1",
    "result":{"name":"工作组1","id":1,"description":"11"}
}
jsonp format:
callback({
    "message":"获取成功",
    "state":"1",
    "result":{"name":"工作组1","id":1,"description":"11"}
})

You can see the difference. The parameter passed from the callback to the background in the url is Shenma. Callback is Shenma. jsonp has one more layer than json, callback(). That way you know what to do with it. So modify the background code.

The backend java code is finally as follows:

copy code
@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, " Get success " , Constants.RESULT_SUCCESS);
    } catch (BusinessException e) {
      e.printStackTrace ();
      result = new ReturnObject(group, " Get failed " , 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;
  }
copy code

Note that the query result needs to be converted into my json format first, and then the parameter callback is used to put another layer outside the json, and it becomes jsonp. Specify the data type of ajax as jsonp for further processing.

Although this solves the cross-domain problem, let's review the reasons for the parsererror. The reason is that the data in json format is blindly treated as data in jsonp format for ajax to process, causing this error. At this time, the server-side code is as follows:

copy code
@RequestMapping(value = "/getGroupById")
  @ResponseBody
  public ReturnObject getGroupById(@RequestParam("id") Long id,
      HttpServletRequest request, HttpServletResponse response){
    String callback = request.getParameter("callback");
    ReturnObject result = null;
    Group group = null;
    try {
      group = groupService.getGroupById(id);
      result = new ReturnObject(group, " Get success " , Constants.RESULT_SUCCESS);
    } catch (BusinessException e) {
      e.printStackTrace ();
      result = new ReturnObject(group, " Get failed " , Constants.RESULT_FAILED);
    }
    return result;
  }
copy code

So far, the first way to solve the ajax cross-domain problem has come to an end.

add a solution

The pursuit is never-ending. In the process of google, I accidentally found a jQuery plugin - jquery-jsonp specially designed to solve cross-domain problems .

With the basis of the first method, it is relatively simple to use the jsonp plug-in, and the server-side code does not need any changes.

Let's take a look at how to use the jquery-jsonp plugin to solve cross-domain problems.

copy code
var url="http://localhost:8080/WorkGroupManagment/open/getGroupById"
    +"?id=1&callback=?";
$ .jsonp ({
  "url": url,
  "success": function(data) {
    $( " #current-group " ).text( " Current working group: " + data.result.name);
  },
  "error": function(d,msg) {
    alert("Could not find user "+msg);
  }
});
copy code

 

So far, the two ways to solve the cross-domain problem have been introduced.

Original address: http://www.congmo.net/blog/2012/06/27/ajax-cross-domain/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326751156&siteId=291194637