How to loop through an JSON associative array in javascript?

前端 未结 6 730
遥遥无期
遥遥无期 2021-02-04 10:50

I\'m getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.

The JSON respons

6条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 11:20

    Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.

    // If you are using jQuery.ajax, you can just set dataType to 'json' 
    // and the following line will be done for you
    var obj  = jQuery.parseJSON( response );
    // Now the two will work
    $.each(obj, function(key, value) {
        alert(key + ' ' + value);
    });
    
    
    for (var key in obj) {
        alert(key + ' ' + response[key]);
    }
    

提交回复
热议问题