The basic principle of

Using the SRC attribute of the script tag, there is no cross-domain restriction. By pointing to an address that needs to be accessed, the server returns a call to a predefined Javascript function. The key point is that the server returns a function that has been defined on the client side.

Implementation analysis

  • Assembled requestedurl
  • generatescriptThe label
  • Defines the output execution resultFunction of cb

Code implementation

Export default function JSONP({url, params = {}, callbackKey = 'cb', callback}) { If no is initialized to 1 json. CallbackId = json. CallbackId | | 1; let callbackId = JSONP.callbackId; / / add to callback to JSON object, avoid pollution window JSON. Callbacks = JSON. Callbacks | | []; JSONP.callbacks[callbackId] = callback; // Add the name to the argument: 'cb= jsonp.callbacks [1]' params[callbackKey] = 'callback'; // Get 'id=1&cb= jsonp.callbacks [1]' const paramString = object.keys (params).map(key => {return ${key}=${encodeURIComponent(params[key])} '}).join('&') // Create script tag const script = document.createElement('script'); script.setAttribute('src', `${url}? ${paramString}`); document.body.appendChild(script); // id increment to ensure unique jsonp. callbackId++; }Copy the code

use

JSONP({
        url: 'myUrl',
        params: {
            id: 1
        },
        callbackKey: 'cb',
        callback (res) {
            console.log(res)
        }
    })
Copy the code