当前位置:网站首页>Jsonp non homologous interaction (click trigger)

Jsonp non homologous interaction (click trigger)

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

When the button is clicked btn1 when , Dynamically create script label , Then assign the request address to src attribute , Add to the page to execute

script There is onload event , When src After the address request script is executed, it will trigger ,so Sure “ burn the bridge after crossing it

Continue to test the request access of different ports

3000 The client file code under port :( Be careful : This time fn2 Parameters can be reserved data Of , Reserved for server delivery )

<body>
    <button id="btn1"> Click me to send a request 1</button>

    <script>
        function fn2(data) {
            alert('fn2 Called ');
            console.log(data);
        }
    </script>

    <script>
        var btn1 = document.getElementById('btn1');
        btn1.addEventListener('click', function() {
            //  establish script label 
            var script = document.createElement('script');
            //  Set up src attribute , take script Append to page 
            script.src = "http://localhost:3001/better?callback=fn2";
            document.body.appendChild(script);
            //  for fear of script Label via btn Infinite clicks trigger and infinite generation , When it is loaded, it is meaningless 
            script.addEventListener('load', function() {
                 //  burn the bridge after crossing it 
                 document.body.removeChild(script);
            })
        })
    </script>
</body>

3001 Port server code :

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

jsonp.get('/better', (req, res) => {
     // Receive... In the request address callback Value , That is, to receive the function name passed by the client 
     const fnName = req.query.callback;
     const result = fnName + '({name:"xx"})';
     res.send(result);
})

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

On the server side : Received the request parameters first callback( At this time, the function name in the request content received by the server is fn2)

                      Then put this function name and   ()  as well as   Parameters   Splicing

                      Last pass send Respond to clients

The server-side response data can also be obtained


原网站

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