【发布时间】:2015-06-23 10:44:29
【问题描述】:
我正在使用 jQuery .click() 更新我的数据库,然后调用我的 AJAX;我的问题是,一旦 SQL 运行了刷新页面内容的最佳方式,我就可以再次执行上一个操作,目前我正在使用window.location.reload(true);,但我不喜欢这种方法,因为我不想让页面重新加载我想要的只是我用来更新它的元素上的内容,以便在 AJAX 成功后匹配数据库字段
这是我的 jQuery:
$(document).ready(function(){
$("span[class*='star']").click(function(){
var data = $(this).data('object');
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success: function(data){
if(data == false) {
window.location.reload(true);
} else {
window.location.reload(true);
}
}
});
console.log(data.art_featured);
});
});
PHP:
<section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column one">
<?php if($row['art_featured']==0){
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star"></span>
<?php
} else if($row['art_featured']==1) {
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star-color"></span>
<?php
}
?>
</div>
</div>
<?php
}
} else {
echo "FAIL";
}
?>
</section>
编辑:
我需要用art_featured 更新.star 或.star-color 类,具体取决于当时art_featured 的值,基本上我在哪里回显art_featured 我需要那个Ajax 成功后重新加载。
编辑:
$("span[class*='star']").click(function(){
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success:function(art_featured){
//remember $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object')),{
art_featured: art_featured
});
}
});
console.log(data.art_featured);
});
【问题讨论】:
-
需要更新的 HTML 元素是什么?我们能看到吗?您能否概述一下元素的哪些部分特别需要更新,以便我们更好地解决手头的问题?
-
您可以使用 json 响应并从匹配的 json 响应中替换旧的 DOM html 或值。
-
@Ohgodwhy 谢谢,我刚刚更新了我的帖子。