(十三)fetch-jsonp处理jsonp字符串(axios不支持jsonp)
jsonp
优势:
1:请求数据没有跨域的限制,后台不用考虑跨域问题
2:对于老版本浏览器更加支持
缺陷::
1:只支持get请求,不支持其他所有方式的请求(请求方式受到了限制)
2:只支持get请求,不支持post(不安全因素一)
3:因为没有跨域,所以调用接口方不能限制ip,安全方面不是很到位(不安全因素二)
总结:如果服务端是支持跨域的,一般都会选择json,不会选择jsonp
使用方式:
1:安装jsonp的模块,后面加上--save方便移动项目的时候也能使用模块
npm install fetch-jsonp --save
npm uninstall fetch-jsonp --save 卸载
2:服务端接口配置
[Route("JsonpList")]
[HttpGet]
public ContentResult JsonpList(string myCallBack, string userName)
{
List<people> peoples = new List<people>() {
new people() { name="zhangsan",no="111"} ,
new people() { name="李四",no = "222" }
};
return Content(String.Format("{0}({1});", myCallBack, JsonConvert.SerializeObject(peoples)));
}
3:页面层请求页面
(1)在main.js里面注册jsonp的全局变脸
import fetchJsonp from 'fetch-jsonp';
app.config.globalProperties.fetchJsonp=fetchJsonp;
(2)定义页面html代码
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item.name }}--{{ item.no }}
</li>
</ul>
<br /><br /><br />
<button @click="getJsonpGet()">axios的get获取jsonp数据</button>
(3)在data里面定义list
data() {
//把业务逻辑得数据渲染到页面上
return {
list: [],
};
},
(4)在methods:里面定义方法
getJsonpGet() {
var that = this;//因为then后面是function不是箭头函数,所有呢里一定要把this提出来,否则直接在下面使用this.list=json,会出现list无效,(最好是不定义that,在.then后面直接使用箭头函数, .catch后面也使用箭头函数)
this.fetchJsonp(
"http://localhost:43597/api/Test/JsonpList?userName=zhangsan",
{
jsonpCallback: "myCallBack",
}
)
.then(function (response) {
return response.json();
})
.then(function (json) {
that.list = json;
})
.catch(function (ex) {
console.log("parsing failed", ex);
});
},
改成箭头函数( (response) =>)过后的getJsonpGet就可以在.then里面使用this了
getJsonpGet() {
this.fetchJsonp(
"http://localhost:43597/api/Test/JsonpList?userName=zhangsan",
{
jsonpCallback: "myCallBack",
}
)
.then( (response) =>{
return response.json();
})
.then( (json) =>{
this.list = json;
})
.catch( (ex)=> {
console.log("parsing failed", ex);
});
},
注意点:
在getJsonpGet方法里面,因为then后面是function不是尖括号,所有呢里一定要把this提出来,否则直接在下面使用this.list=json,会出现list无效,(最好是不定义that,在.then后面直接使用箭头函数 .catch后面也使用箭头函数))
分类:
vue-
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现