How to read json response as name value pairs in JQuery

☆樱花仙子☆ 提交于 2019-11-27 16:38:28

问题


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"};

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  
    }
});

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?


回答1:


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.




回答2:


It's easy like this:

json = {"key1": "value1", "key2": "value2" };

$.each(json, function(key, value) { alert(key + "=" + value); });



回答3:


You can just use responseData['name1']. Easy.



来源:https://stackoverflow.com/questions/3858698/how-to-read-json-response-as-name-value-pairs-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!