Reading JSON with JQuery : Field Names
I have a json payload like below;
{ "ABW": "Aruba", "AFG": "Afghanistan", "AGO": "Angola" }
As you see, it will have all countries. I can read a JSON payload as it is mentioned here;
http://webhole.net/2009/11/28/how-to-read-json-with-javascript/
One problem here is that, how am I going to read the Country Codes here? They will change for every each value. 开发者_运维百科
My goal here is to assign the Country code to value property of the option and country name to text of the option in a select list.
No need for any jQuery. Good ol' plain javascript to the rescue:
var countries = { "ABW": "Aruba", "AFG": "Afghanistan", "AGO": "Angola" };
for(code in countries){
alert("code: " + code + "\n" + "country: " + countries[code]);
}
Fiddle: http://jsfiddle.net/maniator/2adKZ/
When JQuery uses the each function the index is made up of the name of the first bit of information So in { "ABW": "Aruba", "AFG": "Afghanistan", "AGO": "Angola" } the Index for the first object will be "ABW" and the value "Aruba"
var countries = { "ABW": "Aruba", "AFG": "Afghanistan", "AGO": "Angola" }
$.each( countries , function(index) {
var code = index;
var country = countries[index]
})
or
$.each( countries , function(index) {
var code = index;
var country = this;
})
Can you change the response structure? to (maybe):
{"countries":[{"code":"ABW","name":"Aruba"},{"code:"AFG","name":"Afghanistan"}]}
Why not just make it an an array of objects, and then loop through each?
{"results" : [
{countryCode : "ABW",
country : "Aruba"},
{countryCode : "AFG",
country : "Afghanistan"}]
Then loop through each object in your array to get the country code and country name.
精彩评论