1

我正在尝试从 PHP 获取一个数组并使用 jQuery 进一步操作它。在我的 PHP 文件中echo json_encode($data),当我在 jQuery 的响应中添加警报时,我得到:

[
    {
        "CustomerID": "C43242421",
        "UserID": "432421421",
        "Customer": "rqewrqwreeqwr",
        "Add1": "rqwerqwreqwrqwrqwr",
        "Add2": " ",
        "Add3": " ",
        "Phone": "4131231",
        "Fax": "532442141",
        "Contact": "reqwrqwrw",
        "Email": "gfdgdsg",
        "PaymentTerm": null,
        "Country": "3231",
        "City": "111",
        "Zip": " "
    }
]

,这是一个有效的 json 数组。现在我尝试进一步做的是将这些对作为键 => 值,就像我在 php 中的关联数组中一样。

$.post("templates/test.php",
    {data: query,
     cond: $(this).text(),
     action: 'select'
     },
function(res) {
    alert(res) //outputs what i pasted above
    $.each($.parseJSON(res), function(key, value) {
        alert(key + value);
        //this outputs: 0[object Object]
});

删除$.parseJSON上面的函数会给我一个invalid 'in' operand e on jquery.min.js(line 3)Firebug 错误日志。你能帮我解决我的麻烦吗?

4

5 回答 5

4

尝试:

var r = $.parseJSON(res);

$.each(r[0], function(key, value) {
        alert(key + value);

});
于 2013-03-05T14:00:25.827 回答
1

的结果$.parseJSON(res)是一个数组,包含一个元素(一个对象)。当您迭代该数组时(使用$.each),value表示存储在数组当前索引处的整个对象。您需要遍历该对象以输出其属性:

$.each($.parseJSON(res)[0], function(key, value) {
    alert(key + ' = ' + value);
});

如果您有一个包含多个对象的数组,则此更通用的代码应输出所有对象的键值对:

$.each($.parseJSON(res), function(index, arrayObject) {
    $.each(arrayObject, function(key, value) {
        alert(key + ' = ' + value);
    });
});
于 2013-03-05T14:01:58.540 回答
0
res = $.parseJSON(res);

for (var i = 0; l = res.length; i < l; i++) {
   data = res[i];
   customer = data.Customer;

}

你有一个对象数组。您可以像上面的代码一样遍历对象数组。

于 2013-03-05T14:00:49.003 回答
0

试试这个:

$.getJSON('your-json-string-file.php', function (data) {

  $.each(data, function(key, val) {
    alert(key +'=>'+ val)
  });

});

希望对你有帮助

于 2013-03-05T14:03:18.573 回答
0

您可以从 json 中获取某种对象:

function parse_json(res)
{
  try{
    return eval('(' + response + ')');
  }
  catch(e){
    // invalid json
  }
}
于 2013-03-05T14:03:45.373 回答