jQuery - 解析 JSON 数据 - 变量名称遇到问题
我第一次深入研究 JSON 数据的使用。 不过我有一些使用 jQuery 的经验。
我正在发布到此 URL(tumblr api):jyoseph.com/api/read/json
我想做的是输出返回的 json。 到目前为止我所拥有的:
$(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< /a>
tumblr 上的一些键中有“-”连字符,这似乎会导致问题。 正如您所看到的“photo-url-500”或另一个“photo-caption”导致脚本中断,它输出 NaN。
键名称中包含连字符是否有问题? 或者我对这一切都错了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果名称中包含破折号,您将需要以不同的方式访问它们。 将
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 readvar photo500 = this["photo-url-500"];
.请注意,最好不要在每次迭代中追加。 最好附加到字符串或推送到数组,然后在迭代器完成后附加一次。 附加到 dom 的成本很高。
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.
使用括号符号访问成员:
Use the bracket notation to access the members: