Native JS simply encapsulates JSONP to get data across domains

Encapsulating a simple JSONP with native JS is mainly used to understand how the front end implements JSONP.

 

JSONP cross domain requests data across domains by using the src attribute of < img > < script > and the href attribute of < link > to link external websites.

Submit the cross domain request links and parameters to the server in the form of links, and attach the function name of the local receiving JSONP data function in the links. When the server finishes finding the data, call the function, and transfer the data out in the form of function parameters.

 

First of all, using JSONP cross domain, instead of directly returning a data object, it provides the server with a local callable function fn, which is called by the server, and injects the parameters of FN into the cross domain requested data object. That is to say, cross domain data request is to submit the function name of the local function used to accept the JSONP data object to the server, which will call it.

Secondly, because JSONP is frequently used in web pages, there will be many local functions used to receive JSONP data, resulting in code redundancy and resource occupation.

Therefore, take the following methods to receive the data from the cross domain request of JSONP:

1. A variable name fn is randomly generated in the encapsulation function Fun;

2. Save fn as the attribute of the encapsulation function Fun (that is, Fun[fn]), or the global attribute of window;

3. Submit fn to the server as the function name of receiving JSONP function locally;

4. Define the anonymous function that receives JSONP data locally, and assign the anonymous function to the attribute fn(Fun[fn] = function(data) {...}) that encapsulates the function Fun;

5, transmit the data received in the anonymous function, or call the callback function introduced by the encapsulation function (if any) in the anonymous function.

6. Remove the Fun[fn] attribute, that is, destroy the receive function.

In this way, it can not only solve the problem that the local callback function used to receive JSONP is easy to duplicate, but also destroy the callback function after each execution to reduce code redundancy.

 1 <script>
 2     /* 
 3      * Encapsulate JSONP 
 4      * url: Cross domain address
 5      * callback: Callback function to process data
 6      */
 7     function getJSONP(url, callback) {
 8       if (!url) { // url Empty, exit
 9         return;
10       }  
11 
12       // Function name of randomly generated tool function
13       var fnName = '_JSONP'+ parseInt(Math.random()*100);
14       // Change the unassigned function name to getJSONP Because the function name is submitted as a string, after the change here url Submitted in cb=getJSONP._JSONPXX. XX Two randomly generated numbers
15 var jsonp_attr = 'getJSONP.' + fnName; 16 17 // judge url Does the address contain'?' 18 // Baidu server JSONP Callback function key Property is'cb',To match the link below, use'cb=',The actual situation depends on the interface provided by the server 19 if (url.indexOf('?') === -1) { 20 url += '?cb=' + jsonp_attr; 21 } 22 else{ 23 url += '&cb=' + jsonp_attr; 24 } 25 26 27 28 // Dynamic creation script Label 29 var script = document.createElement('script'); 30 // by script Label src Property assignment 31 script.src = url; 32 33 // Define tool functions and assign them to getJSONP Properties of fnName 34 getJSONP[fnName] = function (data) { 35 try { 36 // Cross domain success, processing data through callback function 37 callback && callback(data); 38 } catch (error) { 39 // 40 } 41 finally{ 42 // After the completion of data processing, delete the tool functions and realize the dynamic generation of cross domain script Label 43 delete getJSONP[fnName]; 44 script.parentNode.removeChild(script); 45 } 46 } 47 48 49 // Will be dynamically generated script Label added to DOM,This step makes a cross domain request 50 document.getElementsByTagName('head')[0].appendChild(script); 51 } 52 53 // Use packaged getJSONP function 54 // Get input in Baidu search field"iPhone"Automatically complete the data returned by the function, and delete the callback in the original link 55 getJSONP('https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=1436,31325,21091,31424,31341,31464,30824,31164&wd=iPhone&req=2&csor=6&pwd=iph&_=1588427887099', function (data) { 56 console.log(data); 57 }); 58 </script>

Tags: Javascript Attribute IE JSON

Posted on Tue, 05 May 2020 16:58:33 -0400 by knashash