【问题标题】:JSON.parse Error after decoding JSON.stringify-ed Array解码 JSON.stringify-ed 数组后的 JSON.parse 错误
【发布时间】: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() 一切都很好。但我想知道它如何影响响​​应?
  • 我添加了一个带有解释的答案。如果它对您的问题有所帮助,请随时接受。

标签: php json form-data


【解决方案1】:

当 jQuery 试图解析来自 ajax 调用的响应时,会出现该错误消息。

在您的 ajax 请求中,您设置了:dataType: 'json',它告诉 jQuery 期望响应是一个 json 字符串。然后,jQuery 将尝试将该 json-string 解析为 json-object(使用 JSON.parse())。

但是,由于您的 PHP 代码中有 print_r($sourceInstance),因此响应将不是有效的 json 字符串,并且会使 JSON.parse() 失败。

任何服务器端的输出(echo、var_dump、print_r 等)都将成为响应的一部分。

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 2019-12-09
    • 2014-07-06
    • 1970-01-01
    • 2019-02-04
    • 2018-03-10
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多