我正在尝试使用
jQuery.ajax({})
来运行 PHP 文件。我所有的 ajax 请求都不会执行,只会永远处于挂起状态。
我看过很多不同的解决方案,但没有一个有效。
let account= [{email: null, pass: null, accountType: null}]
function logIn() {
account.email = document.getElementById("emailInput").value;
account.pass = document.getElementById("passwordinput").value;
if(account.email.substring(0,1) === '1'){
account.accountType = "student";
} else if (account.email === ''/* admin email*/) {
account.accountType = "super";
} else {
account.accountType = "teacher";
}
$.ajax({
url:"logIn.php",
type: "POST",
data: {
email: account.email,
password: account.pass,
accountType : account.accountType
},
success: function (data) {
//do something
}
});
}
上面的代码只是从 HTML 中的 <input>
字段获取用户输入。然后计算出 accountType 并尝试运行 ajax 文件。当我调试程序时,ajax 语句根本不执行任何操作。 php 文件甚至没有运行一行。我不知道是什么阻止了请求的工作。这种情况发生在 Firefox 和 Chrome 上。PHP文件供参考:
<?php
$conn = mysqli_connect("localhost", "root", "root", "mentorDB");
if($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$email = $_POST['email'];
$password = $_POST['password'];
$accType = $_POST['accountType'];
if ($accType == 'student') {
$query = "SELECT `student_email`, `user_pass` FROM `students` WHERE `student_email` LIKE ? AND `user_pass` LIKE ?";
$stmt = $conn->prepare($query);
if ($stmt === false) {
die('Error preparing query: ' . $conn->error);
}
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
//Fetch result rows as associative arrays
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($data);
$conn->close();
} elseif ($accType == 'teacher') {
$query = "SELECT `teacher_email`, `user_pass` FROM `teachers` WHERE `teacher_email` LIKE ? AND `user_pass` LIKE ?";
$stmt = $conn->prepare($query);
if ($stmt === false) {
die('Error preparing query: ' . $conn->error);
}
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
//Fetch result rows as associative arrays
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($data);
}
网络控制台如下所示:
主要是想知道我的 JS 代码中是否有某些东西使 ajax 请求永远处于挂起状态。如果这个代码不好,我很抱歉,我在高中,这对我来说都是新的。