我认为这更多地取决于时间而不是代码,所以我真的在寻找关于如何最好地获得 JSON 响应的最佳实践建议。
<script type="text/javascript">
$(window).load(function() {
$('#messages').append('<img src="images/loading.gif" alt="Currently Loading" id="loading" />');
var ideaid = <?php echo $_GET['ideaid']; ?>;
$.ajax({
url: 'sql/ajaxsql.php',
type: 'POST',
data: 'switch=commentList&ideaid=' + ideaid + '&filter=sortdate',
dataType: 'json',
success: function(result) {
var len = result.length;
var html;
console.log('length= ' + len);
$('#response').remove();
console.log(result);
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture&type=small" align="middle" />';
var authname;
FB.api('/' + result[i].user_id + '?fields=name', function(AuthName) {
console.log(AuthName);
alert(AuthName.name);
authname = AuthName.name;
});
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + authname + '<br><hr><hr></p>';
$('#comms').append(html);
}
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
</script>
使用此代码,它会触发以获取有关某个想法(idea_id)的评论。评论仅包含用户 ID (facebook)。当所有数据都返回时,成功然后将准备好以某种顺序打印到屏幕的数据排序。
作为成功的一部分,我在每条评论下都有日期、时间、FB 图片和名称作为作者信息的一部分。
日期和时间,有效。使用图表的图像有效,但名称在窗口加载时有点晚,因此错过了它的调用,所以返回未定义,然后弹出带有名称的警报。我知道ajax就是为了做到这一点。
解决这个问题的最佳方法是什么。
先感谢您。
安德鲁
编辑
即使有以下建议,我也无法完成这项工作。
再次编辑刚刚看到 bf 新的更新版本如下。也会奏效的。但是我在这个功能上花了一天时间,不敢玩。
一旦 FB.api 发挥作用,我就无法从它的外部获取值。所以我采取了不同的方法。
我没有使用 ajax,而是使用 PHP 端的查询来获取数据,包括 uid,然后 json 对其进行查询,并将其固定到 (mysql_fetch_array) 数组中,如下所示:
$gc_result = mysql_query($gc_query);
while ($result = mysql_fetch_array($gc_result)) {
$jsonURL = "https://graph.facebook.com/" . $result['user_id'] . "/";
$json = json_decode(file_get_contents($jsonURL), true);
$result["name"] = $json['name'];
$data[] = $result;
}
echo json_encode($data);
现在我有了它,然后我可以执行以下操作并在 jQuery 中调用它:
for(var i = 0; i < len; i++) {
var pic = '<img src="https://graph.facebook.com/' + result[i].user_id + '/picture?type=small" align="middle" />';
html = '<p>' + result[i].comment + '<br><hr>Date Added: ' + result[i].date + ' by ' + pic + ' ' + **result[i]['name']** + '<br><hr><hr></p>';
$('#comms').append(html);
}
这一切都很好,我是一个完全的 jquery 编程和使用 Facebook API 和 JSON 的新手,但即使我坐下来,对这个解决方案印象深刻。在我得意忘形之前,在性能或安全方面是否存在任何潜在缺陷???
再次感谢提前。
安德鲁