开发者

Foreach in JS with JSON

开发者 https://www.devze.com 2023-04-13 03:47 出处:网络
I get a JSON Object from my PHP: { \"Data\":{ \"Recipes\":{ \"Recipe_7\":{ 开发者_运维问答\"ID\":\"7\",

I get a JSON Object from my PHP:

{
"Data":{
       "Recipes":{
                    "Recipe_7":{
                  开发者_运维问答               "ID":"7",
                                 "TITLE":"Wurstel"
                               },
                    "Recipe_43":{
                                  "ID":"43",
                                  "TITLE":"Wurstel2"
                                 }
                 }
        },
"Message":null,
"Code":200
}

and i want to parse it in JS to get the id and the title

My Code:

  var obj = jQuery.parseJSON(xmlhttp.responseText);

 $.each(obj, function(){

 document.getElementById("txtHint").innerHTML = this.recipes.toString();
 });

The problem is that i always get UNDEFINED

My Quest:

How to parse the obj to get the titel and the id of each Recipe


var obj;

try {
    obj = jQuery.parseJSON(xmlhttp.responseText);
} catch (e) {
   // Invalid JSON
}

if (obj) {
    var recipes = obj.Data.Recipes;

    for (var x in recipes) {
        // recipes[x].ID
        // recipes[x].TITLE
    }
}

As you're already using the jQuery library, you might want to look at using the AJAX module in jQuery. It stops you worrying about the browser differences (XMLHttpRequest vs ActiveX) etc.

You can then use the .getJSON() method, and you'll receive a parsed response for you, making things slightly easier:

jQuery.getJSON('yourUrl.php', function (obj) {  // obj is now a JS object
    var recipes = obj.Data.Recipes;

    for (var x in recipes) {
        // recipes[x].ID
        // recipes[x].TITLE
    }        
});

If you're adament you want to use jQuery.each, replace:

var recipes = obj.Data.Recipes;

for (var x in recipes) {
    // recipes[x].ID
    // recipes[x].TITLE
}  

with:

jQuery.each(obj.Data.Recipes, function () {
    // this.ID
    // this.TITLE
});

Be vary aware that JavaScript is case sensitive; DATA !== Data and ID != id.


var obj = jQuery.parseJSON(xmlhttp.responseText);

// assign outside of loop.
var str = "";

// append to str variable each iteration
$.each(obj.Data.Recipes,function(){
   str += this.ID + "<br />";
   str += this.TITLE + "<br />";
});

// moved outside of loop, because innerHTML would've been overwritten every iteration.
document.getElementById("txtHint").innerHTML = str;


You can use the jQuery each method like this

$.each(obj.Data.Recipes, function(i, item){
    // get each Recipe via the item variable. like item.ID or item.TITLE        
});

However, when you are inside the loop, your innerHTML = would not work as you would only ever display the last recipe.

You would want to build up a string based on the item.TITLE then assign this to the innerHTML of txtHint. As you are using jQuery you can just use $('#txtHint').html(value);

0

精彩评论

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