网站首页php
使用fetch接口访问,及处理options请求
发布时间:2018-08-18 09:29:32编辑:slayer.hover阅读(4175)
1. 使用fetch取代jquery的ajax接口访问,提交json参数并返回json数据。
<div id="app">
{{dataset.msg}}
</div>
<script src="./js/vue.min.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
FetchData_url: 'https://127.0.0.1/index/',
params:{
id: 100
},
dataset: {},
},
methods: {
init: function(){
fetch(FetchData_url,{
method:"POST",
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(vm.params)
}).then(function(res){
return res.json();
}).then(function(data){
if( data.ret==0 ){
vm.dataset = data;
}
}).catch(function(ex) {
console.log('parsing failed', ex)
});
}
}
})
window.onload = function(){
vm.init();
}
</script>2. 结果发现每一次post请求都会先发送一个options 请求,大概是因为发送了自定义header的原因,
既然无法取消,那就在后端设置一下,收到options请求直接返回好了,不浪费服务器资源。
在后端PHP入口文件加上请求判断:
#跨域处理
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods: PUT,POST,GET,OPTIONS,DELETE");
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type,
Accept, Connection, User-Agent, Cookie");
#yaf的判断
if(Yaf_Dispatcher::getInstance()->getRequest()->getMethod()=='OPTIONS'){exit;}
#原生PHP的判断
if($_SERVER['REQUEST_METHOD']=='OPTIONS'){exit;}3.使用promise封装fetch
a. 引入promise库
<script src='promise.js'></script>
b.定义post函数, (api.showProgress,api.hideprogress,$api.getStorage源于apicloud)
var ajax = function (url, pageparm = {}, showLoading=false) {
if(showLoading){
api.showProgress({
title: '提示',
text: '加载中...',
modal: false
});
}
pageparm.token = $api.getStorage('token') ? $api.getStorage('token') : '';
return new Promise(function (resolve, reject) {
fetch(url, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: pageparm,
}).then(function(response) {
response.json().then(function (data) {
if(showLoading) {
api.hideProgress();
}
if(data.ret==0){
resolve(data);
}else{
reject(data);
}
})
}).catch(function(ex) {
if(showLoading) {
api.hideProgress();
}
api.toast({
msg: '获取数据失败,请检查网络',
duration: 2000,
location: 'bottom'
});
});
});
};c.使用方法
var result = ajax(my_url, pageparm, 1).then(function (data) {
console.log(data) //成功处理
},function (err) {
console.log(err) //错误处理
});
评论