问题: .ajax()
不与onclick
一起工作。
当我点击Delete
,这应该发生:
- 删除
MySql
数据库中的行 - 用
id="39"
隐藏元素 重定向到
index
页面。到目前为止我写的是:
index.php
file:
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<span class="delete_test" onclick="del_fn(39)" id="39">Delete</span>
<script>
function del_fn(test_id){
var x = confirm("Are you sure you want to delete?");
if (x)
{
$.ajax({
type:'POST',
url:'test7.php',
data:'delete_id='+test_id,
success:function(data) {
if(data) {
document.getElementById(test_id).style.display = "none";
window.location = 'https://www.example.com';
}
}
});
}
else
{
return false;
}
}
</script>
test7.php
file:
session_start();
include("connect.php");
$id_delete = mysqli_real_escape_string($db_mysqli,$_POST['delete_id']);
$db_mysqli->query("DELETE FROM table Where id = '$id_delete'");
我认为问题出在if(data)
部分。
我会怎么做:
- 在
test7.php
文件中增加一些逻辑,检查查询是否正确执行,echo
是否退出true
或false
。 - 然后在
success
处理程序中检查if(data == 'true')
并在那里继续执行逻辑。
下面是一个简单的例子:
-
on
test7.php
:if(<check if query went okay here>) { echo json_encode(true); } else { echo json_encode(false); }
-
ajax
部分:$.ajax({ url: path, type: "POST", dataType: "json", data: data, cache: false, success: function(response) { if(response === false) { // something went wrong with the query... } else { // query seems okay... } } });
setTimeout(function () {
window.location = 'https://www.example.com';
}, 1);
希望有帮助!