Ajax--使用JSONP向非同源服务器请求数据(优化1)点击按钮才请求,请求地址附有函数名

JSONP代码优化
1、客户端需要将函数名称传递到服务器端
2、将script请求的发送变为动态请求

3000端口的.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>03使用jsonp向非同源服务器请求数据(2).html</title>
 6 </head>
 7 <body>
 8     <button id='btn'>点我发送请求</button>
 9     <script>
10         function fn2(data){
11             console.log('客户端的fn函数被调用了');
12             console.log(data);
13         }
14     </script>
15     <script type="text/javascript">
16         //获取按钮
17         var btn=document.getElementById('btn');
18         //为按钮添加点击事件
19         btn.onclick=function(){
20             //创建script标签
21             var script=document.createElement('script');
22             //设置src属性
23             script.src="http://localhost:3001/better?callback=fn2";
24             document.body.appendChild(script);
25         }
26     </script>
27 </body>
28 </html>

3001端口的app.js

 1 const express=require('express')
 2 const path=require('path')
 3 const app=express()
 4 app.use(express.static(path.join(__dirname,'public')))
 5 
 6 //
 7 app.get('/test',(req,res)=>{
 8     const result='fn({name:"张三"})';
 9     res.send(result);
10 })
11 //03使用jsonp向非同源服务器请求数据(2).html
12 app.get('/better',(req,res)=>{
13     var attr=req.query.callback;
14     if(attr=='fn2'){
15         s=res.send('fn2({name:"张三"})')
16     }
17 })
18 
19 app.listen(3001)
20 console.log("服务器启动成功,端口号为3001")

运行结果:

猜你喜欢

转载自www.cnblogs.com/technicist/p/12792142.html
今日推荐