我有以下代码:
<div id="uniquefriends">
<?php
$friends = $helper->getuniqueUser($uid, $TOKEN);
foreach($friends as $friend) {
echo $friend; // Facebook UID
}
?>
</div>
<a href="#" id="other"><img src="bilder/arrow_otherfriends.png" style="height: 30px;" alt="load other friends" /></a>
<script>
$(document).ready( function() {
$('#other').click(function() {
$.ajax({
type: 'POST',
url: 'otherfriends/',
data: { uid: "<?php echo $uid; ?>", token: "<?php echo $TOKEN; ?>" },
cache: false,
success: function(result) {
$('#uniquefriends').html(result);
},
});
});
});
</script>
描述:
$friends = $helper->getuniqueUser($uid, $TOKEN);
正在获取用户/me/的所有 friend 并将其与数据库进行比较,array_diff()向我展示了 friend 与已经使用该应用程序的用户的差异。
你可以想象,调用这个函数会产生巨大的过载,所以最好不要多次调用它。
这个函数每次调用只给我 4 个 uid (array_slice($array, 0, 4)) (可以修改)
问题:
当用户单击“<a href="#" id="other"><img src="bilder/arrow_otherfriends.png" style="height: 30px;" alt="load other friends" /></a>
”时,将生成下一组用户并作为结果给出(请参阅ajax调用)。
ajax 调用如下所示:
<?php
if(isset($_POST['uid']) && !empty($_POST['uid'])) {
$uid = $_POST['uid'];
$token = $_POST['token'];
$helper = new helper();
$friends = $helper->getuniqueUser($uid, $token);
foreach($friends as $friend) {
echo $friend;
}
}
?>
所以我每次都会打电话"$friends = $helper->getuniqueUser($uid, $TOKEN);"
当用户单击链接时。性能下降,等待时间很长。
我可以以某种方式改进这段代码,不那么频繁地调用这个函数吗?有什么选择吗?
最佳答案
您可以在由 AJAX 调用的 PHP 脚本中实现一个小型缓存系统。
每次调用getUniqueUser
时,都会将结果与输入值配对存储在某个位置( session 、文件、数据库、它们的组合)。
如果输入值在缓存中已知,则只需从中获取结果并立即返回,否则,启动该函数并将丢失的结果存储在缓存中。
当然,您可能需要一个复杂的缓存,跟踪请求的时间戳以避免返回“过时的” friend (也许您最近添加了新 friend 并且需要更新缓存)。这只是一个起点,但如果您不想一直调用相同的函数,则需要某种形式的缓存。
关于php - Jquery Ajax/PHP - 多次调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16166568/