如何在更新成功后使用ajax和重定向页面更新mysql
当点击链接update
更新后mysql重定向到member.php
index . php
<a onClick="update()" id="1">update<a>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
id: $(this).data('id')
};
$.ajax({
type: 'POST',
url: 'update.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
update.php
<?php
include('connect.php');
$id = $_POST['id'];
mysql_query ("UPDATE member SET number = '' WHERE id=$id");
?>
<script language="javascript">
window.location.href = "member.php"
</script>
首先添加class来点击
<a onClick="update();" id="1" class="clickable">update<a>
然后返回响应:-
$query = mysql_query ("UPDATE member SET number = '' WHERE id=$id");
if($query)
echo 'success';
那么成功
success: function(response) {
window.location.href = "member.php";
}
那么完整的代码将是:-
<a onClick="update()" id="1" class="clickable">update<a>
<script type="text/javascript">
function update(){
$.ajax({
type: 'POST',
url: 'update.php',
data: {id: $(".clickable").attr('id')},
success: function(response) {
//$('.clickable').hide(); // hide not possible on redirect
window.location.href = "member.php";
}
});
}
</script>
update.php
<?php
include('connect.php');
$id = $_POST['id'];
$query = mysql_query ("UPDATE member SET number = '' WHERE id=$id");
if($query)
echo 'success';
?>
您不需要重复请求。只要改变你的更新。Ph值如下:
<?php
include('connect.php');
$id = $_POST['id'];
mysql_query ("UPDATE member SET number = '' WHERE id=$id");
header('Location: http://www.example.com/member.php'); // Here you need to give your actual path where you want to redirect.
exit;
?>
使用AJAX和JSON回答,这样你就可以在任何你想重定向的时候没有问题,并使用对象从PHP到你的JS流:
你不必在你的DOM上使用js事件,只有用你的js你才能实现它,它会使你的代码更可重用,因为它会使它免于硬编码变量:
index . html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class="clickable" href="update.php" id="1">update</a>
<script type="text/javascript">
$('.clickable').on('click', function(e) {
e.preventDefault();
var link = $(this);
var data = {
id: link.attr('id')
};
$.ajax({
type: 'POST',
url: link.attr('href'),
data: data,
dataType: 'json',
success: function(response) {
console.log(response);
if (response.result) {
console.log('All done!');
} else {
console.log('Something went wrong!');
}
if (response.redirect != 'undefined') {
window.location.href = response.redirect;
}
}
});
});
</script>
</body>
</html>
然后,在PHP中,你需要返回一个JSON值来获取答案:
update.php
<?php
include('connect.php');
$id = $_POST['id'];
$data = array();
if ( mysql_query ("UPDATE member SET number = '' WHERE id=$id") ) {
$data['result'] = true;
$data['redirect'] = 'http://example.com/redirect_to_ok_place';
} else {
$data['result'] = false;
$data['redirect'] = 'http://example.com/redirect_wrong_result';
}
echo json_encode($data); die();
?>
注意,如果你想从PHP获得值,你的AJAX文件必须完成并回显你的响应,并且你必须有一个格式良好的json,所以,如果没有显示,检查控制台你得到的值,如果你之前回显了一些东西。
最后,重要的是要指出你绝对不能使用MYSQL_QUERY PHP函数!!被弃用了,这是一个巨大的安全漏洞。使用PDO,或者,如果没有别的办法,使用mysqli扩展。你的代码已经为MySQL注入做好了准备,所以在so中检查它以避免它。