0

我有一个如下所示的 JSON 字符串:

{"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}

在 Javascript 中,我试图按类别(cat1-3)输出字符串,这是我到目前为止的代码。

$.post(loadUrl, function(data){

    $("#result").html("<p>Cat1: " + data.cat1 + "</p><p>Cat2: " + data.cat2 + "</p>");

});

我通常不会使用 JSON(通常是 JSTL),但因为我想学习 AJAX,所以我想尝试通过键输出 cat1-3 值,我一直得到“未定义”。

我以此作为获取值的指南:http ://www.skill-guru.com/blog/2010/01/27/json-javascript-tutorial/

4

2 回答 2

3

Try below script

va response =  {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}

var obj = jQuery.parseJSON(response);

alert(obj.cat1);

it will return m1

于 2012-05-09T11:55:21.783 回答
1
var a = JSON.parse("{\"cat1\":\"m1\",\"cat2\":[\"d1\",\"d2\",\"d3\"],\"cat3\":[\"m1\",\"m2\",\"m3\",\"m4\"]}"); 

for(key in a)
{
     alert(key);
     alert(a[key]); 
}
于 2012-05-09T11:11:27.487 回答