The original intention of this series of articles is to “let each front-end engineer master the high frequency knowledge, for the work of power”. This is the front end of the 26th cut, I hope friends pay attention to the public number “kite”, armed with knowledge of their minds.

26.1 the json based

As we all know, JSONP is a cross-domain solution, so let’s take a step-by-step look at why JSONP can solve cross-domain problems.

  1. The basic idea

The basic idea of JSONP is to add a < script > element to a web page, ask the server for data, and when the server receives the request, it returns the data in a named callback function. This should be a common way to interpret JSONP requests, but the same-origin policy does not disallow requests to non-same-origin sources, so how can JSONP solve cross-domain problems? It seems to be a very contradictory point.

  1. Why is JSONP cross-domain

From the perspective of the same origin policy, it is true that the embedded < script > request (non-homologous) violates the same origin policy, but in fact, this is because the browser has made some security for convenience, allowing JS files, CSS files, images and other resources from the non-homologous server. This explains why scripts request resources that are clearly cross-domain but still return content, and it is because browsers give some security (allowing third party resources to be embedded in pages) that JSONP was born.

26.2 hand tore the json

After talking about what JSONP is, its basic ideas, and why JSONP can be implemented across domains, let’s implement JSONP.

  1. Globally mount a function that receives data.
  2. Create a script tag and mount handlers on its onload and onError events;
  3. Mount the script tag to the page to initiate a request to the server;
  4. The server receives the passed arguments and outputs the callback function and data as calls.
  5. When script elements receive script code under influence, they are automatically executed.
function createScript(url, charset) {
    const script = document.createElement('script');
    script.setAttribute('type'.'text/javascript');
    charset && script.setAttribute('charset', charset);
    script.setAttribute('src', url);
    script.async = true;
    return script;
}

function jsonp(url, onsuccess, onerror, charset) {
    const hash = Math.random().toString().slice(2);
    window['jsonp' + hash] = function (data) {
        if (onsuccess && typeof(onsuccess) === 'function') { onsuccess(data); }}const script = createScript(url + '? callback=jsonp' + hash, charset);

    Onload and onReadyStatechange are used for compatibility with IE, because Internet Explorer 9 previously did not support onLoad events, only onReadyStatechange events
    script.onload = script.onreadystatechange = function() {
        // If there is no readyState event, it is not Internet Explorer and can be executed directly. Otherwise, it must wait until the state changes to Loaded or complete
        if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
            script.onload = script.onreadystatechange = null;
            // Remove the script DOM object
            if (script.parentNode) {
                script.parentNode.removeChild(script);
            }

            // Delete a function or variable
            window['jsonp' + hash] = null; }}; script.onerror =function() {
        if (onerror && typeof(onerror) === 'function') { onerror(); }}// Add a label and send the request
    document.getElementsByTagName('head') [0].appendChild(script);
}
Copy the code

1. If you think this article is good, share and like it so that more people can see it

2. Pay attention to the public number of kite, and the number of the Lord together to kill the front hundred