Javascript 如何在不刷新的情况下通知数据已更改?
我写了这段代码:Javascript 如何在不刷新的情况下通知数据已更改?,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我写了这段代码: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); $.ajax({ type: 'POST',
$('.actionButton').click(function(){
var buttonValue = $(this).val();
var userId = '<?php echo $_SESSION['id']; ?>';
console.log(userId);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {
'action': buttonValue,
'id' : userId
},
dataType: 'json',
success: [ location.reload()]
});
});
我知道我应该将$id绑定到查询,以避免在任何人开始抱怨之前进行SQL注入。这不是现在的问题
我的问题是:这段代码功能齐全,但当我点击RemoveAll按钮或ReadAll或UnreadAll时,它非常重要。当我的页面刷新时,我知道会发生这种情况,因为我告诉ajax执行location.reload()
,但如果我不这样做,我的表就不会知道数据已经更改
我怎样才能使我的页面在单击按钮时知道数据已更改 诚然,这不是最好的方法,但一个简单的解决方案是只响应您在php文件上所做的任何操作,如下所示:
if(isset($_POST['action'])){
$id = $_POST['id'];
switch($_POST['action']){
case 'removeAll':
removeAll($database, $id);
break;
case 'readAll':
readAll($database, $id);
break;
case 'unreadAll':
unreadAll($database, $id);
break;
default:
break;
}
die($_POST['action']);
}
现在,您的ajax调用者可以这样理解:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {
'action': buttonValue,
'id' : userId
},
dataType: 'json',
success: function (response)
{
if(response =='removeAll')
{
//remove all remove the table by emptying the div or something
}
elseif(response =='readAll')
{
//perform read all action
}
esleif(response =='unreadAll')
{
//perform unreadall action
}
}
});
要更新表,我建议使用用于jquery的datatable插件,它允许您添加/删除行以及更多内容。我建议如下: 首先,您需要确保所有sql查询都正常运行,没有任何问题,最好使用if语句检查查询是否正确,并向ajax请求返回true和false消息。一旦ajax请求成功并且php文件返回您可以使用的真实消息,jQuery hide或remove函数将删除所选消息。这样您就不必重新加载页面。如果有什么不清楚的地方,请告诉我。
我希望这能帮到你 然后让php返回新数据,并使用一个success函数,该函数将使用该数据更新正确的元素。您可以使用
中的来删除相应的tr
。remove()
而不是执行location.reload()
if(isset($_POST['action'])){
$id = $_POST['id'];
switch($_POST['action']){
case 'removeAll':
removeAll($database, $id);
break;
case 'readAll':
readAll($database, $id);
break;
case 'unreadAll':
unreadAll($database, $id);
break;
default:
break;
}
die($_POST['action']);
}
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {
'action': buttonValue,
'id' : userId
},
dataType: 'json',
success: function (response)
{
if(response =='removeAll')
{
//remove all remove the table by emptying the div or something
}
elseif(response =='readAll')
{
//perform read all action
}
esleif(response =='unreadAll')
{
//perform unreadall action
}
}
});