如何在 JQuery 中读取 json 响应作为名称值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3858698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read json response as name value pairs in JQuery
提问by jgg
I want to read json response as name and value pairs in my JQuery code. Here is my sample JSON response that I return from my java code:
我想在我的 JQuery 代码中读取 json 响应作为名称和值对。这是我从 Java 代码返回的示例 JSON 响应:
String jsonResponse = "{"name1":"value1", "name2:value2"};
in my JQuery, if I write jsonResponse.name1
, I will get value as "value1"
. Here is my JQuery code
在我的 JQuery 中,如果我写jsonResponse.name1
,我将获得价值为"value1"
。这是我的 JQuery 代码
$.ajax({
type: 'POST',
dataType:'json',
url: 'http://localhost:8080/calculate',
data: request,
success: function(responseData) {
alert(responseData.name1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//TODO
}
});
Here I want to read "name1"
from jsonResponse instead of hardcoding in JQuery. Something like looping throug the response getting each name and value. Any suggestions?
这里我想"name1"
从 jsonResponse 中读取而不是在 JQuery 中进行硬编码。类似于循环获取每个名称和值的响应。有什么建议?
回答by Darin Dimitrov
success: function(responseData) {
for (var key in responseData) {
alert(responseData[key]);
}
}
It is important to note that the order in which the properties will be iterated is arbitrary and shouldn't be relied upon.
需要注意的是,迭代属性的顺序是任意的,不应依赖。
回答by Arnaud F.
It's easy like this:
这很简单:
json = {"key1": "value1", "key2": "value2" };
$.each(json, function(key, value) { alert(key + "=" + value); });
回答by Jacob Relkin
You can just use responseData['name1']
. Easy.
你可以只使用responseData['name1']
. 简单。