简体   繁体   English

遍历和读取json数据

[英]iterating through and reading json data

I'm using ajax to get a json string from the server then using eval to turn it into an object. 我正在使用ajax从服务器获取json字符串,然后使用eval将其转换为对象。 when I iterate through thejson data I only get the key. 当我遍历json数据时,我只会得到密钥。 How do I get the value of the key. 我如何获得钥匙的价值。 This is what I have: 这就是我所拥有的:

var jsonobj = eval('(' + xmlhttp.responseText + ')');

for (i in jsonobj){
     alert(i);
}

Which alerts the keys. 哪个提示按键。 How do I get the value of the keys? 如何获得钥匙的价值?

使用子脚本符号: jsonobj[i]

try this: 尝试这个:

var jsonobj = eval('(' + xmlhttp.responseText + ')');
var value;

for (i in jsonobj){
     value = jsonobj[i];
}

If the server returns JSON you don't need to use eval. 如果服务器返回JSON,则无需使用eval。 Simply specify the dataType and jQuery will automatically parse the result for you: 只需指定dataType ,jQuery就会自动为您解析结果:

$.ajax({
    url: '/script',
    type: 'POST',
    dataType: 'json',
    success: function(result) {
        for (var key in result) {
            if (result.hasOwnProperty(key)) {
                alert('key: ' + key + ', value: ' + result[key]);
            }
        }
    }
});
var jsonobj = eval('(' + xmlhttp.responseText + ')');

for (i in jsonobj){
    alert(jsonobj[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM