【问题标题】:Ajax json Parser ErrorAjax json 解析器错误
【发布时间】:2013-04-05 00:30:01
【问题描述】:

我不断收到 JSON 解析器错误 (萤火虫控制台说'没有子对象')用于以下数据:

(字符串)每次迭代的 var 数据

var data='['; 
data+=   '{ "title": "  Nac", "no1": "1212","no2": "12126"},';
data+=   '{ "title": "  Nac", "no1": "1212","no2": "12126"},';
data+=   '{ "title": "  Nac", "no1": "1212","no2": "12126"},';
data+= ']';

和javascript解析json

var json = JSON.parse(data)

和 jQuery AJAX 请求

        $.ajax({
        type: "POST",
        data: json,
        url : 'ticket.php',
        dataType: 'json',
        async: false,
        contentType : 'application/json; charset=utf-8',
        error: function(jqXHR, exception) 
        {
            if (jqXHR.status === 0) 
            {
                $('.item').html("err");
            } else if (jqXHR.status == 404) 
            {
                $('.item').html('err!');
            } else if (jqXHR.status == 500) 
            {
                alert("err!");
            } else if (exception === 'parsererror') 
            {
                $('.item').html('err parsererror');
            } else if (exception === 'timeout') 
            {
                $('.item').html('err!');
            } else if (exception === 'abort') 
            {
                $('.item').html('err!');
            } else 
            {
            $('.item').html('err!');
            }
        },
        success : function(data)
        {
            alert("okey");
        }           
    });

ticket.php 完全是空的,因为我不知道如何从 php 中的 ajax 接收 json 数据

任何帮助将不胜感激。 谢谢

【问题讨论】:

  • 我刚刚尝试了JSON.parse,它工作正常
  • 如果你已经设置了datatype=json就不需要解析了。因为它已经将JSON字符串解析为javascript对象了
  • tha 解析错误是因为字符串的最后一个对象之后的 ,(逗号),即最后一个 '{ "title": " Nac", "no1": "1212","no2 ": "12126"}' 你必须用 ] 而不是 ,] 连接数据

标签: jquery ajax json parse-error


【解决方案1】:

JSON.parse 为您提供 JavaScript 对象,如果您在帖子中发送 json,则发送 json 而不是对象。也不是构建一个 json 字符串,而是构建一个对象,然后对其进行字符串化

var data= [{
    "title": "  Nac",
    "no1": "1212",
    "no2": "12126"
},
{
    "title": "New",
    "no1": "12",
    "no2": "121"
},
{
    "title": "San",
    "no1": "1227",
    "no2": "1"
}];
var json = JSON.stringify(data);
        $.ajax({
        type: "POST",
        data: json,
        url : 'ticket.php',
        dataType: 'json',
        async: false,
        contentType : 'application/json; charset=utf-8',
        ...

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 2017-05-08
    • 2014-12-04
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多