概念
浏览器通过<script>标签的src属性请求服务器数据,同时服务器返回一个函数调用,这种请求方式为JSONP
特点:
1 JSONP不属于真正的ajax请求,因为它没有XMLHttpRequest对象
2JSONP仅支持get请求
实现步骤:
- 获取客户端发送来的回调函数名字
- 准备通过JSONP形式发送给客户端的数据
- 根据前两部得到的数据,拼接出函数调用的字符串
- 把字符串响应给客户端的<script>标签解析
app.get('/api/jsonp',(request,response)=>{
//获取回调函数
const funname=request.query.callback
const data={name:'wcg',age:17}
//组合成字符串
const scriptStr=`${funname}(${JSON.stringify(data)})`
//发送
response.send(scriptStr)
})
客户端请求
$.ajax({
type: "get",
dataType: "jsonp",
url: 'http://127.0.0.1/api/jsonp',
success: function (data) {
console.log(data)
}
});