Using jQuery and JSONP to easily solve the problem of cross domain access

  • 2020-03-30 01:35:49
  • OfStack

Time passed quickly, and was pulled back to the js battlefield, the cross-domain problem this scar opened pain.

Fortunately, with the help of jquery, the cross-domain problem seems not so difficult. This time also took the opportunity to cross-domain problem to give the root cause, combined with the actual development project, looked up the relevant materials, is to solve the cross-domain problem.. It is necessary to take notes.

Cross-domain security restrictions are refers to the browser. The server does not exist the cross-domain security restrictions, so similar to the native server through httpclient way of "cross domain access" work done, and then in the browser using AJAX to get the machine on the server side "cross domain access" the corresponding url. The complete cross-domain access can be indirectly. But it is clear that the potential is large, but also have the fewest restrictions, many widgets open platform server side (such as sohu blog open platform) is actually doing? To be outside the scope of this discussion.

Real case:

var qsData = {'searchWord':$("#searchWord").attr("value"),'currentUserId':$("#currentUserId").attr("value"),'conditionBean.pageSize':$("#pageSize").attr("value")};
   url: http:// cross-domain dns/document!searchJSONResult.action,
   type: "GET",
   dataType: 'jsonp',
   jsonp: 'jsoncallback',
   data: qsData,
   timeout: 5000,
   beforeSend: function(){
   //This method is not triggered because the dataType is no longer an ajax event if it is specified as jsonp
   success: function (json) {//The client-side jquery predefined callback function, which is dynamically executed after successful retrieval of the json data on the cross-domain server
    complete: function(XMLHttpRequest, textStatus){
    $.unblockUI({ fadeOut: 10 }); 
   error: function(xhr){
    //This method is not triggered because the dataType is no longer an ajax event if it is specified as jsonp
    //Request error handling
    alert(" Request error ( Please check the status of the relevancy network .)");


$.getJSON(" http:// cross-domain dns/document!searchJSONResult.action?name1="+value1+"&jsoncallback=?",
      if(json. The property name == value ){
      //Execute the code

This is actually the above example $.ajax({.. }) a high-level encapsulation of the API in which some of the underlying parameters of the $.ajax API are encapsulated and not visible.
In this way,jquery will assemble the following url get request
http:// cross-domain DNS /document! SearchJSONResult. The action? & jsoncallback = jsonp1236827957501 & _ = 1236828192549 & E7 searchWord = % % 94% BE E4 A8 % % % 8 b & currentUserId = 5351 & conditionBean pageSize = 15

On the response side (http:// cross-domain DNS /document! SearchJSONResult. Action),
Jsoncallback = request-getparameter ("jsoncallback") to get the js function name:jsonp1236827957501 that the jquery end then calls back
Then the content of response is a Script Tags:"jsonp1236827957501("+ json array generated by request parameters +")";
Jquery calls the js tag:jsonp1236827957501(json array) dynamically through the callback method.
This achieves the purpose of cross - domain data exchange.

The most basic principle of jsonp is: add a < Script> The SRC attribute of a script tag has no cross-domain restrictions. In this case, this cross-domain approach has nothing to do with the ajax XmlHttpRequest protocol.
This makes the "jQuery AJAX cross-domain problem "a pseudo-proposition, and the name of the jQuery $.ajax method is misleading.

If you set it to dataType: 'jsonp', the $.ajax method has nothing to do with the ajax XmlHttpRequest and is replaced by the jsonp protocol.

JSONP is an unofficial protocol that allows for server-side integration of Script tags back to the client, and cross-domain access to JSONP in the form of javascript callback (JSON with Padding). Because of the same origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make the cross-domain request by using the script markup of the HTML and returning the script code to execute in the response, where we can pass the javascript object directly using JSON. This cross-domain communication is called JSONP.

JsonCallback function jsonp1236827957501 (...). : a function that is registered by the browser client and called back after it gets the json data on the cross-domain server

The json principle:

A callback (such as 'jsoncallback') is registered on the client side, and the name of the callback (such as jsonp1236827957501) is passed to the server. Note: after the server gets the value of the callback, use jsonp1236827957501(...) By including the json content to be output, the server can generate the json data to be received correctly by the client.

Then, in javascript syntax, generate a function whose name is the value of the passed parameter 'jsoncallback' jsonp1236827957501.

Finally, the json data is directly placed into the function in the form of input, so that a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is used as the parameter.
Passed to the pre-defined callback function (success: function (json) encapsulated by the jquery $.ajax() method in the example above).

You could say that the way jsonp works is in principle the same as < Script SRC ="http:// cross-domain /... Xx. Js "> < / script> JSONP is a Script Injection behavior, so it also has some security risks.

Although the use of post + to dynamically generate iframes can achieve the purpose of post across domains, this is a more extreme approach and is not recommended.
It can also be said that the cross-domain of get method is legal, and the post method is considered illegal from the perspective of security.

Related articles: