开发者

How to make JSON response data dynamic?

开发者 https://www.devze.com 2023-03-04 14:20 出处:网络
I have the following code which retrieves data with a JSON request: // Replace home page template wildcards with data from database (JSON)

I have the following code which retrieves data with a JSON request:

// Replace home page template wildcards with data from database (JSON)
$.getJSON("mvc/models/home.php?action=getpagecontent&&jsoncallback=?", function(data) {

// Set markup identifiers
var identifiers = new Array(); 
identifiers[0] = "introheader1";      
identifiers[1] = "introtext1";      

// Replace markup on page
for (var x = 0; x < data.length; x++) {  
    if (data[x].introheader1 != undefined){
      $(".introheader1").replaceWith(data[x].introheader1);
    }
    if (data[x].introtext1 != undefined){
      $(".introtext1").replaceWith(data[x].introtext1);
    }
  }  
});

Thi开发者_JAVA技巧s works fine, but is a pain if there a lot of elements returned. So instead of this for every element:

    if (data[x].introheader1 != undefined){
      $(".introheader1").replaceWith(data[x].introheader1);
    }

I want to make it dynamic by replacing the hard coded values with the values from the identifiers array, like this, so I only have to have one and can loop through:

    if (data[x].identifiers[0] != undefined){
        $("." + identifiers[0]).replaceWith(data[x].identifiers[0]);
    }

But it gives an error at the "data[x]." replacements. How can I do this? Thanks!


Change your for to this:

for (var x = 0; x < data.length; x++) {  
  for(var prop in data[x]){
     $("."+prop).replaceWith(data[x][prop]);
  }
}  

Hope this helps. Cheers

0

精彩评论

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

关注公众号