• JSONP


    前端封装方法

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <script>
            function jsonP(option) {
                var callbackName = 'jsonp_' + Math.random().toString().substr(2) +
                    Math.random().toString().substr(2);
                //将用户通过对象命名空间传递进来的函数挂在到全局
                window[callbackName] = function (data) {
                    option.success(data);
                    //这里才以为这可以删除script标签了
                    document.body.removeChild(script);
                }
                //1解决url问题
                //2解决回到处理函数问题
                option.url = option.url + '?callback=' + callbackName;
                var script = document.createElement('script');
                script.src = option.url;
                //将script挂在到body上
                document.body.appendChild(script)
    
            }
            jsonP({
                url: 'http://localhost:3000/',
                type: '',
                data: '',
                success: function (data) {
                    console.log(data)
                }
            })
        </script>
    </body>
    
    </html>

    后端处理

    const express=require('express');
    
    const app=express();
    
    app.get('/',(req,res,next)=>{
        console.log(`收到客户端请求了:${req.url}`)
        var data=JSON.stringify({
            foo:'bar',
            list:[1,2,3,4]
        })
        res.end(`${req.query.callback}(${data})`)
    })
    
    app.listen(3000,()=>{
        console.log('server start and listen at 3000')
    })
     
  • 相关阅读:
    bzoj1904: Musical Water-fence
    bzoj3822: 文学
    bzoj1513: [POI2006]Tet-Tetris 3D
    bzoj4130: [PA2011]Kangaroos
    bzoj2515 Room
    bzoj2518: [Shoi2010]滚动的正四面体
    bzoj4617: [Wf2016]Spin Doctor
    bzoj3086: Coci2009 dvapravca
    bzoj3745: [Coci2015]Norma
    bzoj1837: [CROATIAN2009]cavli 凸包1
  • 原文地址:https://www.cnblogs.com/lvlisn/p/14941769.html
Copyright © 2020-2023  润新知