Laravel 5.4无法解析使用Jquery Ajax发送的FormData javascript对象 [英] Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax
问题描述
最近我一直试图解决一个没有运气的问题,基本上我正在尝试使用AJAX向服务器提交表单,表单有文件,所以我使用的是 FormData
JQuery 1.12中的javascript对象。数据到达服务器,但在我的方式我不知道如何格式化。
Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData
javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
这是我的AJAX功能:
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
当我执行 dd($ request-) > all());
在我的控制器中我得到这样的结果:
and when I perform a dd($request->all());
in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
我尝试过的事情:
- 将HTTP谓词设置为POST。结果相同。
- 设置AJAX
contentType:false
,contentType:application / json
。空响应。 - 删除
enctype:'multipart / form-data'
。相同的回复。
- Set the HTTP verb to POST. Same result.
- Set the AJAX
contentType: false
,contentType: application/json
. Empty response. - Remove
enctype: 'multipart/form-data'
. Same response.
感谢任何帮助。
推荐答案
最后我放弃了尝试让它工作并尝试了更加普遍的方法,我仍然不知道为什么请求被这样形成,但是 XMLHttpRequest()
功能完美,迁移不是什么大问题。
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest()
function works perfectly and the migration is not a big deal.
相当于我发布的函数将是:
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
if (request.status == 200) {
toastr.success('Yai! Saved successfully!');
} else {
toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
};
}
这篇关于Laravel 5.4无法解析使用Jquery Ajax发送的FormData javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!