美文网首页
什么是JSONP

什么是JSONP

作者: 易景平 | 来源:发表于2021-02-14 10:40 被阅读0次

    什么是JSONP

    1. 请求方动态创建script标签,src指向响应方,同时传一个查询参数 ?callbackName=xxx
    2. 响应方根据查询参数构造如:xxx.call(undefined,'你要的数据')这样的响应
    3. 浏览器接收到响应,就会执行xxx.call(undefined,'数据')
      这就是JSONP

    行业约定:

    • callbackName ==> callback
    • xxx ==>随机数 比如:jp128884
    let functionName= 'jp' + parseInt(Math.radom() * 10000)
    window[functionName] = function(){}
    delete window[radomName] //使用完后干掉这个函数,下次使用会生成新的
    

    后端不需要知道前端的具体细节
    后端返回主要数据若为一个JSON,JSON的左边为回调函数部分,右边为).即左边一个padding,右边一个padding,,JSON + padding =JSONP

    这个技术的名字起的很烂!!
    换个好理解的名字可以称之为: 动态标签跨域请求

    1. 原生代码实现JSONP
            let script = document.createElement('script')
            let functionName = 'jp' + parseInt(Math.random() * 10000,10)
            script.src = '/pay?callback=' + functionName
            window[functionName] = function(response){
                console.log('收到数据为:' + response)
                amount.innerText = amount.innerText - 1
                delete window[functionName]
            }
            document.body.appendChild(script)
            script.onload = function(e){
                e.currentTarget.remove()
            }
    
    1. jQuery实现JSONP
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql",
     
        // The name of the callback parameter, as specified by the YQL service
        jsonp: "callback",
     
        // Tell jQuery we're expecting JSONP
        dataType: "jsonp",
     
        // Tell YQL what we want and that we want JSON
        data: {
            q: "select title,abstract,url from search.news where query=\"cat\"",
            format: "json"
        },
     
        // Work with the response
        success: function( response ) {
            console.log( response ); // server response
        }
    });
    

    jQuery里把JSONP放在AJAX里面,但实际上JSONP和AJAX没有关系。

    相关文章

      网友评论

          本文标题:什么是JSONP

          本文链接:https://www.haomeiwen.com/subject/wtlyxltx.html