开发者

Jquery - json parse

How to use foreach parse the json type -

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {

            $(dataid).html(data);
        });
    }

data = {"file":"1","text":"Hello world","name":"Jenan","i开发者_JAVA百科d":"1","url":"url"}

I would get text -

1 - Hello World - Jenan - 1 - url.

Thanks for the advice.


for...in will loop through each object key:

var output = [];
for( var key in data) {
  if (data.hasOwnProperty(key)) {
      output.push(data[key])
  }
}

alert(output.join(' - '));


EDIT

data.url; // the value of url, which happens to be url in this example
// or
data['url']

hasOwnProperty ensures that the key is a direct property of the object.


The $.each() function only works on Arrays and jQuery objects.

Here, data is not an array, its a regular object.

So, get the data from your Json this way :

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {
            $(dataid).html(data.file +' - '+ data.text +' - '+ data.name +' - '+ data.id +' - '+ data.url);
        });
    }

EDIT: If you have some of these objects in an Array like the one that follows :

[{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"},{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"},{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"}]

Do like that :

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {
            $(dataid).html('');
            $.each(data, function(key, value){
                $(dataid).append(value.file +' - '+ value.text +' - '+ value.name +' - '+ value.id +' - '+ value.url +'<br/>');
            });
        });
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜