【发布时间】:2017-07-24 11:43:57
【问题描述】:
我想通过 JSON 提交一个数组数组。所以我创建了一个对象,对其应用 JSON.stringify() 并将其设置为 formData...
var sources = new Array();
$('.source-instance').each(function(){
var auxObject = {};
auxObject["sourceTitle"] = $(this).find(".source-title").val();
sources.push(auxObject);
console.log('sources: ' + JSON.stringify(sources));
});
formData.set('sources', JSON.stringify(sources));
当我检查数据时
console.log(formData.get('sources'))
我明白了
[{"sourceTitle":"SomeTitle"},{"sourceTitle":"AnotherTitle"}]
...然后我通过 AJAX 继续到服务器。
在 php 的服务器端,我循环遍历数组并让它打印:
foreach (json_decode($request['sources'], true) as $sourceInstance) {
print_r($sourceInstance);
}
我明白了
Array
(
[sourceTitle] => SomeTitle
)
Array
(
[sourceTitle] => AnotherTitle
)
看起来不错。但我也得到了
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
这是怎么回事?我该如何修复它?我不知道它是从哪里来的。
编辑 ajax 看起来像这样:
$.ajax({
url: '/piece/store',
type: 'POST',
processData: false,
contentType: false,
dataType: 'JSON',
data: formData,
success: function(response){
if (response.status == 'error'){
// show the erors
}
if (response.status == 'success'){ // "redirect" to success page
window.location.replace('/succes');
}
},
error: function(response){
$(".optional.errors").show();
$('ul.errors').empty();
$.each(response.errors, function (index, error) {
$('ul.errors').append('<li>' + error + '</li>');
});
}
});
php 响应:
$response = [
'status' => 'success',
];
return response()->json($response);
【问题讨论】:
-
该错误消息并非来自您在问题中获得的代码。向我们展示您的 ajax 调用以及您如何处理响应。可能是当您尝试解析响应时(在 ajax 回调中)它失败了,因为您的代码不返回 json(您的 php 代码中有 print_r())。
-
@MagnusEriksson 就是这样。当我删除 print_r() 一切都很好。但我想知道它如何影响响应?
-
我添加了一个带有解释的答案。如果它对您的问题有所帮助,请随时接受。