目录
- JSONP跨域原理演示
- JSONP跨域注意事项
- JSONP实践
- jQuery发送JSONP请求
JSONP(JSON With Padding)是利用script标签的跨域功能,比如script和img的src属性,link的href属性,它只支持get请求。
JSONP跨域原理演示
把外部资源的数据放在html中的div盒子里
<div id="result"></div>
<script>function handle(data){// 获取result元素const result=document.getElementById('result');result.innerHTML=data.name;}
</script>借助src引入外部资源
<script src="./js/app.js"></script>
const data={name:'我是外部资源的数据'
};handle(data);
JSONP跨域注意事项
使用jsonp跨域时,服务端返回数据的不是字符串形式,返回形式是函数的调用,也就是js代码,这样浏览器才能解析并执行。其中函数参数是服务端想给客户端返回的结果数据,函数要提前在前端中声明,然后前端会执行这个函数对数据进行处理。
若response.send('hello jsonp-server');
则报错
前端引用:
<div id="result"></div><script>function handle(data){// 获取result元素const result=document.getElementById('result');result.innerHTML=data.name;}</script><!-- 函数的声明要放在请求之上 -->
<script src="http://localhost:8000/jsonp-server">
后端通过函数调用形式返回数据:
// jsonp服务
app.all('/jsonp-server',(request,response)=>{// response.send('hello jsonp-server'); 会报错,应该返回 函数调用的内容(js代码)response.send('console.log("hello jsonp-server")'); // 正常打印const data={name:'尚硅谷'};// 将数据转化为字符串let str=JSON.stringify(data);// 返回结果response.end(`handle(${str})`) // 用end不用send 因为end不会加特殊响应头
});
JSONP实践
在input
框中输入用户名后,触发onblur
事件时通过新增srcipt
标签的方式向服务端发请求获取数据,把返回的数据信息放在p
标签里
获取数据前:
返回数据后:
用户名:<input type="text" id="username"><p></p><p></p><script>// 获取input元素const input=document.querySelector('input');const p=document.querySelector('p');// 声明handle函数function handle(data){// 把input边框变成红色input.style.border="solid 1px #f00";// 修改p标签的提示文本p.innerHTML=data.msg;}// 绑定事件input.onblur=function(){// 获取用户的输入值let username=this.value;// 向服务端发送请求 检测用户名是否存在console.log(this);// 1. 创建script标签const script=document.createElement('script');// 2.设置标签的src属性script.src='http://127.0.0.1:8000/check-name-server';// 3.将script标签 插入到文档中document.body.appendChild(script);}</script>
// jsonp案例 检测用户名是否存在
app.all('/check-name-server',(request,response)=>{const data = {exist:1,msg:'用户名已经存在'};// 将数据转化为字符串let str=JSON.stringify(data);// 返回结果response.end(`handle(${str})`);
});
jQuery发送JSONP请求
效果:点击按钮发送jsonp请求,返回的数据会展示在div盒子中。
JQuery中的$.getJSON()方法允许通过使用JSONP形式的回调函数来加载其他网域的JSON数据,jQuery会自动生成回调函数的名称。
<button>点击发送jsonp请求</button>
<div id="result"></div>
<script>$('button').eq(0).click(function(){ // ?callback=? 固定写法$.getJSON('http://localhost:8000/jquery-jsonp-server?callback=?',function(data){console.log(data);$('#result').html(`名称:${data.name}</br>校区:${data.hobbies}`)})});
</script>
// jQuery发送jsonp请求
app.all('/jquery-jsonp-server',(request,response)=>{const data={name:'小明',hobbies:['吃饭','唱歌','打球']};// 将数据转化为字符串let str=JSON.stringify(data);// 接收callback参数let cb=request.query.callback;// 返回结果response.end(`${cb}(${str})`)
});