jQuery - 解析 JSON 数据 - 变量名有问题 [英] jQuery - parsing JSON data - Having trouble with variable name

查看:18
本文介绍了jQuery - 解析 JSON 数据 - 变量名有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次深入研究 JSON 数据.不过我有一些使用 jQuery 的经验.

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

我在这个 URL (tumblr api) 发帖:jyoseph.com/api/read/json

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

我想做的是输出返回的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>'); 
      }); 

  }); 

});

请参阅我的 jsbin 帖子以了解整个脚本:http://jsbin.com/utaju/edit

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

来自 tumblr 的某些键中包含-"连字符,这似乎引起了问题.正如您所看到的,photo-url-500"或其他photo-caption"导致脚本中断,它正在输出 NaN.

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?

推荐答案

如果名称中有破折号,您需要以不同的方式访问它们.将 var photo500 = this.photo-url-500; 更改为 var photo500 = this["photo-url-500"];.

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"];.

这篇关于jQuery - 解析 JSON 数据 - 变量名有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆