[JSONP]关于JSONP的几个点

关于JSONP

今天学习到了JSONP,关于JSONP的定义和用法在阮一峰阮老师的博客里讲解得很清楚了,这里只是记录一些关于JSONP的点。

回调函数的命名

在阮老师的博客中举的例子是回调函数命名为foo,在实际使用环境中回调函数一般是搭配着随机数使用,使用时实时生成,使用过后销毁此函数。

如:

//客户端(浏览器)
button.addEventListener('click',(e)=>{
    let script = document.createElement('script')

    //生成随机函数名
    let functionName = 'no1harm' + parseInt((Math.random()*1000000),10)
    window[functionName] = function(result){
        alert(result)
    }
    script.src = 'http://xxx.com:8002/xx?callback=' + functionName
    document.body.appendChild(script)
    script.onload = function(e){
        e.currentTarget.remove()

        // 销毁函数
        delete window[functionName]
    }
    script.onerror = function(e){
        alert('fail')
        e.currentTarget.remove()
        delete window[functionName]
    }
})

// 服务器
...
if( path === '/xx'){
    response.setHeader('Content-type','text/html;charset=utf-8')
    response.statusCode = 200
    response.write(`
        ${query.callback}.call(undefined,'success')
    `)
    response.end()
}
...

JSONP 为什么不支持 POST

因为JSONP是通过动态创建script实现的,而动态创建script只能使用GET,不能使用POST。

JSONP的jQuery使用方式

首先在项目引入jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

然后:

//客户端
button.addEventListener('click',(e)=>{
    $.ajax({
        //要请求的域名
        url: "http://xxx.com:8002/xx",

        dataType: "jsonp",

        //回调函数
        success: function( response ) {
            if(response === 'success'){
                ...
            }
        }
    })
}


//服务器
...
if( path === '/xx'){
    response.setHeader('Content-type','text/html;charset=utf-8')
    response.statusCode = 200
    response.write(`
        ${query.callback}.call(undefined,'success')
    `)
    response.end()
}
...

值得注意的是,虽然这个命名为$ajax,但是他和ajax没有关系,他是jQuery的方法。

原文地址:https://www.cnblogs.com/No-harm/p/9615013.html