作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我得到以下字符串:
[{"Key":1,"Value":"correct"},{"Key":2,"Value":"incorrect"},{"Key":3,"Value":"incorrect"},{"Key":4,"Value":"correct"},{"Key":5,"Value":"incorrect"}]
我想根据 TR 的 ID 在 JSON 中是否具有“正确”或“不正确”值来更改 TR 的背景颜色。
如何从 JSON 中获取单个项目的值?我尝试过:
success: function (result) {
// update with results
//alert(JSON.stringify(result));
//$('#myDiv').html(JSON.stringify(result));
// non of these work
alert(result[0]);
alert(result[key]);
},
最佳答案
您可以使用$.each()
来迭代对象数组。
$.each(result, function(i, item) {
alert(item.Key);
});
在对 $.each()
的回调中,item
将是对正在迭代的数组中当前项的引用。
然后您只需使用正常的属性访问即可获取 Key
属性的值。
当然,您也可以使用传统的 for
语句来循环数组。
for (var i = 0; i < result.length; i++) {
var item = result[i];
alert(item.Key);
}
<小时/>
所有这些都假设您的响应具有正确的 Content-Type
设置,或者您已将 dataType:"json"
赋予 $.ajax()
.
关于javascript - 使用 jQuery 从 JSON 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785540/
我是一名优秀的程序员,十分优秀!