1. 必考面试,什么是JSONP
原生JS:
button.addEventListener('click',(e)=>{
let script = document.createElement('script');
let functionName = 'frank'+parseInt(Math.random()*100000,10);
window[functionName] = function (result) {
if(result === 'success'){
amount.innerText = amount.innerText - 1
}else {
alert(`fail`)
}
};
script.src = 'http://jack.com:8002/pay?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]
}
});
请求方:frank.com的前端程序员(浏览器)
服务器:jack.com的后端程序员(服务器)
- 请求方创建一个script标签,它的src指向服务器的ip地址,同时传一个查询参数(?callback=functionName)
- 服务器通过
这句话是精髓response.write(` ${query.callback}.call(undefined,'success') `)
'success'是JSON,左边的叫左padding,右边的括号叫右padding,合起来叫JSONP
这样来调用请求方的callback函数,名字是functionName - 浏览器接到success的响应就会执行functionName函数
2. 必考面试题:JSONP为什么不支持POST请求
答:JSONP是通过动态创建script的方法进行的,而script只能发送get请求不能发送post请求。
3. jquery的写法
jsonp不是ajax
$.ajax({
url:"http://jack.com:8002/pay",
dataType: "jsonp",
success:function (response) {
if(response === 'success'){
amount.innerText = amount.innerText-1;
}
}
})