问题描述
我想在我的JQuery代码中将JSON响应读取为名称和值对.这是我从Java代码返回的示例JSON响应:
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:
String jsonResponse = "{"name1":"value1", "name2:value2"};
在我的JQuery中,如果
写入jsonResponse.name1
,则将得到"value1"
的值.这是我的JQuery代码
in my JQuery, if I write jsonResponse.name1
, I will get value as "value1"
. Here is my JQuery code
$.ajax({
type: 'POST',
dataType:'json',
url: 'http://localhost:8080/calculate',
data: request,
success: function(responseData) {
alert(responseData.name1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//TODO
}
});
在这里,我想从jsonResponse中读取"name1"
,而不是在JQuery中进行硬编码.诸如循环遍历响应以获取每个名称和值之类的东西.有什么建议吗?
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?
推荐答案
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.
这篇关于如何在JQuery中将JSON响应读取为名称值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!