It is indispensable to deal with ajax in the work. To avoid making more wheels, normally we just use the ajax function of jQuery. Ajax in the same origin is known to use the xhr (XMLHttpRequest) requests. In jquery, jsonp requests are also called ajax, only the parameters are different, but in fact, cross-domain jsonp request is actually a fundamentally different concept, jsonp does not use xhr request at all

Due to the limitations of the same-origin policy, cross-domain cannot be completed. The jsonp request actually creates a script request dynamically in the web page, which is equivalent to creating a GET request, and will not be subject to cross-domain restrictions. For example, a jsonp request is initiated from the domain name abc.com to api.abc.com , Is actually dynamically added in the page

<script src="http://api.abc.com"></script>

It should look like this under a little encapsulation:

function jsonpRequest(url){
  var script = document.createElement('script');
  script.src = url;
  document.getElementsByTagName('body')[0].appendChild(script);
}

How to pass parameters and get the data returned by the server? Passing parameters is very easy to solve. It is enough to pass parameters directly through url, and to get the data returned by the server requires certain processing by the server. Here the server needs to return not json data, but a call to a js callback method, such as jsonCallback( {code:0}), and this callback function needs to be defined in the page.

function jsonpCallback(data){
  console.log(data.code);
}

In this way, the callback method returned by the server will be executed directly after the script request is completed, which is the method we defined above.

In fact, there may be more than one jsonp request on our page. It may be troublesome to define a callback method for each individual request. Back-end may also complain that it is troublesome to define a specified calling method for each interface. In fact, we can Pass the callback method name as a parameter to the backend, and the callback method can also be generated by random numbers (jquery practice)

var jsonpCallbackNum = 1;
function jsonpRequest(url, callback){
  jsonpCallbackNum ++;
  var randomCallback = 'jsonpcallback' + jsonpCallbackNum;
  window[randomCallback] = callback;
  var script = document.createElement('script');
  spliter = url.indexOf('?') !== -1 ? '&' : '?';
  script.src = url + spliter + 'jsoncallback=' + randomCallback;
  document.getElementsByTagName('body')[0].appendChild(script);
}

Well, it’s not difficult to implement, but I’ve just written a demo, and the actual business may need to define the above code according to requirements.