zoukankan      html  css  js  c++  java
  • 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')
    })
     
  • 相关阅读:
    watch 一些实际用法(vue)
    如何动态渲染多个echart图表小结(vue)
    webstorm 合并代码冲突后如何唤起代码合并弹窗方案
    jQuery Mobile
    响应式布局
    Angularjs
    项目经理PPT演讲意见
    创业者自己摸索总结的12条建议
    关于网站建设
    调研方案如何炼成?
  • 原文地址:https://www.cnblogs.com/lvlisn/p/14941769.html
Copyright © 2011-2022 走看看