The method of requesting data package jsonp

What is jsonp: 

Jsonp (JSON with Padding) is a json "use mode" that allows it to obtain information from other web domain name (website), that cross-domain data is read.

Why do we need a special technique different domain (website) to access data from (JSONP) it? This is because the same-origin policy.

Same-origin policy, it is a well-known security policy proposed by Netscape, now all JavaScript-enabled browsers will use this strategy.

 

Jsonp look at the api: 

 

 

Method of packaging jsonp:

//jsonp.js file 

Import from originJsonp 'JSONP' // initially introduced JSONP // first parameter for the interface address url. // The second parameter data is carried back interface address parameters. Because jsonp does not support direct transfer an object. So, we need to separate the url and pass parameters. We call this approach will be more convenient time. // third parameter corresponding api above opts opts Export default function JSONP (url, data, opts) { // splicing and url parameters need to pass data. // first determine url back there? No, no, then behind the increase? , Plus some behind the words & url + = (url.indexOf () <0: "&" "?"? "?") + Param (the Data); // function jsonp we need to return a Promise return new new Promise ( (Resolve, Reject) => { originJsonp (URL, the opts, (ERR, Data) =>(! ERR) { Resolve (Data) } the else { Reject (ERR) } }) }) }
// packaging a method, splicing out the dismantling of the object behind the url Export function param (Data) { the let url = "" ; for ( var k in the Data) { // if data [k] is undefined, then it returns empty the let value = data [k] == undefined data [k]:!? "" ; // we use encodeURIComponent () encoding the URI at url + = & $ `{K} = $ {the encodeURIComponent (value)}`; } // If the url is not empty, if desired, first a & omitted. return url ? url.substring(1) : ""; }

 

 

Instructions:

// package just introduced jsonp method 
Import from jsonp './jsonp.js'

the getData () { const URL
= "HTTP: // XXXXXXXX" ; const Data = { name: 'zhangsan' , Age: 12 is }; const the opts = { param: 'jsonpCallback' }; JSONP (URL, Data, the opts) .then (RES => { IF (res.code === 0 ) { the console.log (res.data); } }) }

 

Guess you like

Origin www.cnblogs.com/littleSpill/p/11520246.html
Recommended