gpt4 book ai didi

php - jQuery AJAX成功后刷新页面内容

转载 作者:行者123 更新时间:2023-12-01 04:54:31 25 4
gpt4 key购买 nike

我正在使用 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>

编辑:

我需要更新类(class).star.star-colorart_featured取决于 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);
});

最佳答案

如果您可以在 MySQL 数据库成功后返回 art_featured,它会将其发送回 ajax 成功函数。在这里,我们可以操作数据,但是,首先我们应该存储对被单击元素的引用。

var data = $(this).data('object');
var $this = $(this); //add this line right after the above

现在,在我们的 success 函数中,不使用 data,而是使用 art_featured,因为这就是我们返回的全部内容。现在我们可以更新目标上现有的数据对象。

success:function(art_featured){
//remmeber $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object'),{
art_featured: art_featured
}));
}

上面将扩展现有的数据对象,允许根据我们正在扩展的对象重新定义键:值对。

您应该发现它按预期工作。

关于php - jQuery AJAX成功后刷新页面内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15630158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com