开发者

JSON object recognized as String by jQuery

I'm trying to parse some JSON coming from an AJAX request using jQuery.

Basically, the JSON is encoded by PHP and looks like:

{"1":{"key1":"value1","key2":"value2"},"0":{开发者_JAVA技巧"key1":"value1","key2":"value2"}}

The callback function of $.ajax looks like:

$.each(data, function(item) {
      console.log($.type(item));
      myfunction(item.key1);
      });

item is recognized as a string and item.key1 is undefined.

The content-type of the response is "application/json" so jQuery is supposed to parse it. data is then recognized as an object.

So… what's wrong?


The item is a String.

The first argument of the callback of $.each() is the key. In your example, your JSON object is an Object with numerical indexes, except in strings. You are attempting to access the property from the property name. Instead, you'd want to use data[item] in your example.

You want to access the property values like so...

$.each(data, function(propertyName, propertyValue) {
      console.log(propertyName, propertyValue);
});

Variables names have been changed to be clearer.

In a real Array, the arguments would be be the index followed by the value.


If it is valid JSON it should be ok.

By the looks of the object returned you might have to use:

item.1.key1
//Or
item['1'].key1

Instead of:

item.key1

Try that and see what you get.


Try setting the type to json:

$.ajax({
  dataType: 'json'
});


When reviewing the response from the server using Firebug, did you see JSON "tab" for the call? If not, you must add die(); to the end of the PHP script generating the JSON for jQuery to recognize it as such. Without die(), jQuery saw it as a string and I was unable to parse it properly.

I know this question is old, but I hope the answer can help someone else since this problem was a real head-scratcher for me too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜