vuejs使用vue-resource发送ajax请求代码:
methods: {
fillIn: function (index, n) {
var formData = new FormData();
var itemId=this.items[index].id;
this.items[index].publishing_days = n;
formData.append('publishing_days', n);
this.$http.patch('/article/'+itemId, formData,{
before(request) {
if (this.previousRequest) {
this.previousRequest.abort();
}
this.previousRequest = request;
}
}).then((response) => {
}, (response) => {
});
}
}
这是ajax请求发送的数据截图:
ArticleController
public function update(Request $request, $id)
{
$article = Article::findOrFail($id);
dd($article);
dd($request->publishing_days);
}
问题:dd($request->publishing_days);
的结果是null,怎么回事呢?
ringa_lee2017-05-16 16:53:02
这是因为header头的问题,web服务器无法处理put, patch和delete这种rest风格的请求,启用该选项后,请求会以普通的post方法发出;
在vue-resource文档中,有这样一句话:
Send PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header
所有我们在代码中加上这个属性并将值设置为true即可:
this.$http.patch('/demo', formData, {emulateHTTP: true});
再对比一下header头:
加上属性后:
X-CSRF-TOKEN:ngenvCDnCOXWkQqbLjIdSo7Ekq7wjfLg0TqUMNcu
X-HTTP-Method-Override:PATCH
X-Requested-With:XMLHttpRequest
加上属性前:
X-CSRF-TOKEN:ngenvCDnCOXWkQqbLjIdSo7Ekq7wjfLg0TqUMNcu
X-Requested-With:XMLHttpRequest