当前位置:网站首页>Jsonp function encapsulation

Jsonp function encapsulation

2022-06-25 19:42:00 Xibing_ G

encapsulation jsonp The factors that function needs to consider :

( Involving parameter transfer -> function + Request parameters , Need to be encapsulated jsonp Add parameter )

function jsonp(options) {}

1、script Label creation

 var script = document.createElement('script');

2、 The parameters to be passed in the request address 、 Splice the parameters

var params = '';
// options Medium data The value is the request parameter to be passed , Is to key=value&key1=value1 To deliver , So further operation is needed 
for (var attr in options.data) {
    params += '&' + attr + '=' + options.data[attr];
}

3、 Avoid function coverage caused by multiple calls to functions with the same name --> Use random nomenclature ; You need to remove the decimal point of the random number

【 Be careful 】: As mentioned below myJsonp It's casual , The main purpose is Make the function names different , however It can't just be numbers

//  Remove the points from the generated random number , And then the function name 'myJsonp' The splice is assigned to fnName
var fnName = 'myJsonp' + Math.random().toString().replace('.', '');

4、  Change the function to script Functions that can be called

       Function to success It means carrying out success() You can also execute this function .

      but:script The script cannot be executed success Of , Because it is not a global scoped function

      so: To change to global scope , That is to say window Next , To use [ ] The format of , Can't use . The format of

      Only properties that do exist on the object can be used ., and Variables can only be used [ ]

window[fnName] = options.success;

5、 Set function name 、 Parameters are spliced into the request address , Then assign the request address to script Of src value

      Passing the function name along with the arguments avoids “ Manually control that the function names of the server side and the client side are consistent ” Trouble

      So dependent on , One on the server side req.query.callback You can get the dynamic function name

 script.src = options.url + '?callback=' + fnName + params;

6、 take script Append to page

document.body.appendChild(script);

7、 Avoid multiple calls that result in script Multiple creation of , When triggered onload After the event, delete it from the page

script.addEventListener('load', function() {
      document.body.removeChild(script);
})

Call encapsulated jsonp function

The server 3000 client html Code :

<body>
    <button id="btn1"> Click me to send a request 1</button>
     <script>
        var btn1 = document.getElementById('btn1');
        btn1.addEventListener('click', function() {
        jsonp({
                //  Request address 
                url: 'http://localhost:3001/better',
                //  Request parameters 
                data: {
                    firstname: 'xibing',
                    age: 18
                },
                success: function(data) {
                    alert('My name is:' + data.name);
                }
            })
        })
    </script>
</body>

The server 3001 Code :( Add the function name and ( Parameters ) Splicing , And then through send Respond to clients )

const express = require('express');
const jsonp = express();

jsonp.get('/better', (req, res) => {
    const fnName = req.query.callback;
    //  Transform the data sent by the client 
    const name = req.query.firstname + '_G';

    //  Attention format : Within the object key Corresponding value It needs to be wrapped in double quotation marks 
    // const result = fnName + '({name:"xibing_G"})';
    const result = fnName + '({name:"' + name + '"})';
    res.send(result);
})


jsonp.listen(3001);
console.log('3001 Monitored ');

(1)、 There are... In the client transfer request parameters firstname:xibing

(2)、 Server through req.query.firstname Receive and modify , And then put it in the function as an actual parameter response to the client  

(3)、 The client executes the response function ( There are already arguments added by the server )

(4)、 Last : A pop-up window in the function body pops up the contents of the client + The data transformed by the server to the parameters passed in by the client .

(5)、 among : The client gets the response content 【 function fnName(.....)】 Start to call the response result ,

                        Because it has been success Put in global , So here we call success No problem at all .

The principle is :

        script It will send a request to the server and execute the contents of the server response

        Client side transfer function , The function is modified through the server ( for example : Transfer argument )

        The client passes in the arguments and calls this function ( In order to call , Put the function under the global in advance )

原网站

版权声明
本文为[Xibing_ G]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190516374088.html