gpt4 book ai didi

javascript - AJAX不会提交数据

转载 作者:行者123 更新时间:2023-11-28 06:20:52 26 4
gpt4 key购买 nike

我正在学习 AJAX。我们本周的任务是使用 Ajax 提交表单。但是我似乎无法弄清楚我做错了什么,因为它不会提交。

PHP 可以独立运行。并且它需要作为备份选项可用,以防 JavaScript 被禁用。

<?php

$final_content='';

if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){

$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO testTable (Name, Lastname, Email)

VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."";
}

$conn->close();


}else {
$final_content = '<form action="script.php" method="post" id="user_form">

<input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
<input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
<input type="email" name="u_email" placeholder="Email" id="user_email"> <br>

<input type="submit" value="Submit" name="submit">
</form>';
}
?>

<html>
<head>

<script type="text/javascript" src="jquery-1.11.2.min.js"></script>


<script>
$(document).ready(function(){

//Set form variable
var form = $("#user_form");

form.submit(function(event){

//Set data variables
var user_name = $("#user_name").val();
var user_lastname = $("#user_lastname").val();
var user_email = $("#user_email").val();

//Check if values are set
if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){

$.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){

$("#results").html(data);

});
}

event.preventDefault();
});

});
</script>

</head>

<body>



<div id="results"></div>

<?php echo $final_content ?>

</body>


</html>

最佳答案

试试这个:

 $.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){
$("#results").html(data);
});

将上面的行替换为以下代码:

$.post("script.php", {u_name: user_name,u_lastname: user_lastname,u_email: user_email}, function(data){
$("#results").html(data);
});

有关 $.post() 函数的不同选项的更多详细信息,您可以引用以下链接: http://api.jquery.com/jquery.post/

关于javascript - AJAX不会提交数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541283/

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