gpt4 book ai didi

javascript - Ajax 脚本不起作用

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

我有一个ajax请求,它仍然加载php脚本,而不是在不刷新的情况下执行其功能。我猜我的 ajax 有问题,下面是 ajax 脚本的问题

HTML

<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' value='$ad_id'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>

Ajax 请求

$('#connect_form').submit(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});

PHP 脚本

require_once("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect'])) {
$my_id = $_SESSION['log_id'];
$ad_id = $_POST['conn_id'];
$rand_num = rand();
$hsql = <<<EOF
SELECT COUNT(hash) as count FROM connect WHERE(user_one = '$my_id'
AND user_two = '$ad_id') OR(user_one = '$ad_id'
AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1) {
$response = "Your are already connected to '$ad_id'";
} else {
$csql = <<<EOF
INSERT INTO connect(user_one, user_two, hash) VALUES('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db - > exec($csql);
if (!$cret) {
echo "Error connecting to '$ad_id'";
} else {
echo "Successful";
}
}
}

表单会执行,但不会刷新页面。请问ajax有什么问题?

最佳答案

我建议您使用 serialize() 方法发送序列化的表单data

此外,对 form 使用 submit 事件:$('form').on('submit', function (e) {}

$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: $('form').serialize()
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});

关于javascript - Ajax 脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297256/

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