嗨,我需要一些帮助。我目前正在学习Ajax和Json,所以我没有太多经验。
我按照本教程进行操作,以便在不刷新页面的情况下获取数据,但我对此有一些担忧。
脚本工作正常,我发现的唯一问题是,如果我点击刷新,则需要大量时间(大约 5-10 秒)才能再次加载内容。在Firebug中,我可以在控制台中看到它一直在绑定,因为它一直在发送请求。这是代码.HTML
<div class="ajax_results">
<ul id="results"></ul>
</div>
PHP脚本
$query = "SELECT `img_id`, `image_name`, `title` FROM `images` ORDER BY `img_id` DESC LIMIT 5 ";
$run = mysqli_query($connection, $query) or die(mysqli_error($connection));
$json = array();
while ($row = mysqli_fetch_array($run, MYSQLI_ASSOC)) {
array_push($json, array('image_name' => $row['image_name'],
'title' => $row['title']));
}
echo json_encode(array("json" => $json));
和 JS
$(document).ready(function() {
refresh();
});
function refresh() {
setTimeout(function() {
update_content();
refresh();
}, 200);
}
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src='"img/uploads/"+this['image_name']+"'" /><br />"+this['title']+"</li>");
});
});
}
这是个问题吗??我可以以某种方式改进代码吗?任何帮助将不胜感激
提供一些额外的反馈。如果将 $.getJSON 直接放置在 $(document).ready(function() 中,则内容加载速度更快,但如果发生任何更新,例如标题中不会显示而不刷新页面。 我真正想要实现的是加载内容,如果发生任何更改,则在不刷新页面的情况下显示它们。
这是解决问题的另一种方法
$(function() {
update_content();
});
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src='"img/uploads/"+this['image_name']+"'" /><br />"+this['title']+"</li>");
});
setTimeout(function(){
update_content();
}, 1000);
});
}
在这里,我将 setTimeout 调用移动到 update_content() 函数中,并增加了超时以给浏览器更多的喘息空间,我个人不会每秒调用它,但这只是一个示例,我可能会使用 10 秒甚至更长时间。
如果您不希望它反复触发,请删除整个 setTimeout 块。
$(function() {
update_content();
});
function update_content() {
$.getJSON("fetch_data.php", function(data) {
$("ul#results").empty();
$.each(data.json, function() {
$("ul#results").append("<li><img src='"img/uploads/"+this['image_name']+"'" /><br />"+this['title']+"</li>");
});
});
}