开发者

how to read jquery ajax returned object with out a loop

Given the following jquery ajax request:

$.getJSON("getSearchSystems.php", {level: "full", data:this.label}, function(data){
     //This method does not work.
     console.log(data.regionName);
     console.log(data.constellationName);
     console.log(data.solarSystemName);

     //This method does work
     $.each(data, function (i, elem) {
        console.log(elem.regionName);
        console.log(elem.constellationName);
        console.log(elem.solarSystemName);
    });

});

Output:

undefined
undefined
undefined
The Bleak Lands
Sasen
Kuomi

JSON response from PHP script

[{"regionName":"The Bleak Lands","constellationName":"Sasen","solarSystemName":"Kuomi"}]

I cannot seem to figure out how to access this objects data with out iterating 开发者_开发知识库over it. Is there not a way to do this without a loop?

I would like to be able to access the data like var regionName = data.regionName


try

 console.log(data[0].regionName);

just dont ask why but some times the data is returned as array and is to be accessed like data[0]


If you want to loop your server needs to send an array, like this:

[ { regionName: 'r1', constellationName: 'c1', solarSystemName: 's1' }, 
  { regionName: 'r2', constellationName: 'c2', solarSystemName: 's2' } ]

Looking at those undefined values that your are getting I suspect that the first element of this array doesn't contain any regionName, constellationName and solarSystemName properties and it looks something like this:

[ { someIrrelevantProperty: 'foo bar', someOtherirrelevantProperty: 'baz' }, 
  { regionName: 'The Bleak Lands', constellationName: 'Sasen', solarSystemName: 'Kuomi' } ]


Does your request always return json object array like your json dump?

If so, you always get undefined when you call console.log(data.regionName); without iteration since your raw data is an array and you try to reference json array's undefined property.

However, if you are trying to check for a specific value like error checking value, results count, or some other value relevant with your business; you have to response with an object that contains your data array among with the other values you needed. Like this;

{"object1":"value1", "object2":[{"regionName":"The Bleak Lands","constellationName":"Sasen","solarSystemName":"Kuomi"}]}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜