这是ajax调用返回的json:
{
"StumbleUpon": 0,
"Reddit": 0,
"Facebook": {
"commentsbox_count": 0,
"click_count": 0,
"total_count": 0,
"comment_count": 0,
"like_count": 0,
"share_count": 0
},
"Delicious": 0,
"GooglePlusOne": 1,
"Buzz": 0,
"Twitter": 1,
"Diggs": 0,
"Pinterest": 0,
"LinkedIn": 1
}
Run Code Online (Sandbox Code Playgroud)
我正试图在jquery中处理它但由于某种原因我无法理解,Facebook.total_count是未定义的.我会期待,否则因为控制台告诉我上面的json被收到了.而且,所有其他人(data.Twitter等)都有效.这是我的回调函数,其中产生错误.我究竟做错了什么?
function(data){
console.log(data);
//this line throws the error
var fb = data.Facebook;
var total = parseInt(data.Twitter + parseInt(fb.total_count) + data.GooglePlusOne + data.Pinterest + data.LinkedIn);
// rest of code.
}
Run Code Online (Sandbox Code Playgroud)
请参阅jsFiddle上的代码.
从根本上说,该代码有效 - 只要data已经反序列化.如果没有,要么......
...添加dataType: "JSON"到ajax呼叫:
$.ajax({
// ...
dataType: "JSON",
// ...
});
Run Code Online (Sandbox Code Playgroud)
...或者使用$.parseJSON结果.
function(data) {
if (typeof data === "string") {
data = $.parseJSON(data);
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
注意:您不需要parseInt对这些数字使用它们,它们已经是JSON中的数字,并且将被正确反序列化.
| 归档时间: |
|
| 查看次数: |
2778 次 |
| 最近记录: |