JSONP principle and simple implementation

The full name JSON with Padding, for a solution to solve the problem of cross-domain AJAX.

Since the same-origin policy restrictions, browser XmlHttpRequest request only allows current source (domain name, protocol, port) of resources, but there is no limitation on the request script resources. Is achieved by cross-domain request requesting script tag, and then outputs the data on the server and JSON callback function, this embodiment is referred to as cross-domain data JSONP.

The principle

1. First, a client registered callback method, placed on the window object, such as:

callbackFunction (json) {
    console.log(JSON)
}

Then the callback name (callbackFunction) to the server.

2. Mr. servers into JOSN data.

3. JOSN data directly into the reference mode, the function is placed, thus generating a js syntax documents (e.g. callbackFunction (JOSN)), back to the client.

4. client browser, returns the JS-tag is inserted into the DOM, parses the script tag, performs callbackFunction (JOSN).

In this way, you can get cross-domain data.

{} from JSONP Import './JSONP'
 // call 
JSONP ({ 
  URL: 'URL' , 
  Data: {   
    key1: 'key1'   
  },   
  the callback (Data) {   
    // Data is returned from the server data   
  }   
})
// JSONP.js
let JSONP = (config = {}) => {
  let { data, url, callback } = config
  // 拼接请求Url
  if (!url) throw new Error('url is required!')
  let name = `id_${(new Date()).getTime()}_${Math.random().toString().substr(2)}`
  let srcUrl = getSrcUrl(url, {
    data,
    callback: name
  })
  // 插入Script标签
  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = srcUrl
  script.id = name
   // the CallBack objects into the window, the call destroy 
  window [name] = function (JSON) {
     // After performing this function, to destroy the function 
    window [name] = undefined
     // element gets the script of 
    var elem = document.getElementById (name)
     // delete head inserted inside script, which is a three-step order not to affect the entire DOM contamination ah 
    removeElem (elem)
     // perform a function passed 
    the callback && typeof the callback === ' function '&& the callback (JSON) 
  } 
  var head = document.getElementsByTagName (' head ' )
   IF (head head && [0  ]) {
    head [0].appendChild(script)
  }
}
let getSrcUrl = (url, data) => {
  let _url = url + (url.indexOf('?') === -1 ? '?' : '&')
  let ret = ''
  if (typeof data === 'string') {
    ret = data
  } else if (typeof data === 'object') {
    for (let key in data) {
      ret += '&' + key + '=' + encodeURIComponent(data[key])
    }
  }
  ret = ret.substr(1)
  return _url + ret
}
let removeElem = (elem) => {
  let parent = elem.parentNode
  if (parent && parent.nodeType !== 11) {
    parent.removeChild(elem)
  }
}
export default JSONP

note

  1. In jquery in, JSOP is encapsulated in the  $.ajax() process, but his realization of the principle and  ajax completely different.
  2. JSONP compatibility is better, can run more ancient browser, no XMLHttpRequest or ActiveX support.
  3. JSONP only supports GET request without support and other types of HTTP POST requests.
  4. JSONP when the call failed does not return a variety of HTTP status code (Workaround: Add the timeout parameter, although JSONP request itself of error is not caught, but in the end because of a timeout to perform error correction).
  5. When using JSONP JSONP service must be used to ensure the security must be credible. In case of services provided JSONP page injection vulnerability exists, it returns javascript will be executed if they are injected which is very dangerous.

Guess you like

Origin www.cnblogs.com/Nyan-Workflow-FC/p/11221224.html