jQuery - parsing JSON data - Having trouble with variable name

混江龙づ霸主 提交于 2019-12-21 01:40:11

问题


My first delve into working with JSON data. I have a bit of experience using jQuery though.

I'm posting to this URL (tumblr api): jyoseph.com/api/read/json

What I'm trying to do is output the json that gets returned. What I have so far:

$(document).ready(function(){ 

$.getJSON("http://jyoseph.com/api/read/json?callback=?", 
  function(data) { 
    //console.log(data); 
    console.log(data.posts);         

      $.each(data.posts, function(i,posts){ 
        var id = this.id; 
        var type = this.type; 
        var date = this.date; 
        var url = this.url; 
        var photo500 = this.photo-url-500; 

        $('ul').append('<li> ' +id+ ' - ' +type+ ' - ' +date+ ' - ' +url+ ' - ' +photo500+ ' - ' + ' </li>'); 
      }); 

  }); 

});

See my jsbin post for the entire script: http://jsbin.com/utaju/edit

Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN.

Is there a problem with having hyphens in the key names? Or am I going about this all wrong?


回答1:


If there are dashes in the names you'll need to access them differently. Change var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"];.




回答2:


Please note it is best not to append inside each iteration. Better to append to a string or push to an array then append once after the iterator has finished. Appending to the dom is expensive.




回答3:


Use the bracket notation to access the members:

var photo500 = this['photo-url-500']; 


来源:https://stackoverflow.com/questions/1231447/jquery-parsing-json-data-having-trouble-with-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!