我花了一周时间试图解决这个问题,但没有成功。 Google 和 ChatGPT 都没有帮助。类似的问题似乎不同,不足以解决我的问题。
addUser() 函数的 AJAX 返回错误:而不是成功:。我收到的消息(如下所列)表示存在解析错误和语法错误。我找不到任何语法错误,我不确定解析出了什么问题。我觉得我以前以完全相同的方式使用 JSON 没有问题,但突然我遇到了这个问题。
发生的另一件奇怪的事情是错误响应文本是其中一个 php 文档 (data-in.php) 的完整代码。
我现在很迷茫,我什至不知道如何解决这个问题。我还需要提供哪些其他信息?我是否忽略了一些显而易见的事情?我需要做得更好吗?
这是我从“错误:”得到的响应:
两个主要文件是data-in.php和data-out.php。
data-in.php 代码:
<?php
include_once 'header.php';
?>
<div class="container mx-auto h-full w-full items-center grid grid-cols-1">
<div id="form" class="flex flex-col mx-auto gap-2 w-1/4 border rounded-lg p-4 bg-gradient-to-r from-indigo-200 via-purple-200 to-pink-200">
<input id="userName" name="username" type="text" placeholder="Username" class="input form-control-lg border border-2">
<input id="email" name="email" type="text" placeholder="Email" class="input form-control-lg border border-2">
<input id="pwd" name="pwd" type="password" placeholder="Password" class="input form-control-lg border border-2">
<input id="pwdConfirm" name="pwdconfirm" type="password" placeholder="Cofirm Password" class="input form-control-lg border border-2">
<input id="submitSignup" name="submit" type="submit" value="Sign Up" class="btn btn-primary text-xl form-control-lg border-none bg-gradient-to-r from-pink-700 via-purple-700 to-indigo-700">
<div id="error"></div>
</div>
</div>
<script>
$(document).ready(function()
{
// ON KEYBOARD ENTER
$(".input").keyup(function(event)
{
if (event.which === 13)
{
$("#submitSignup").click();
}
});
// ON SUBMIT
$("#submitSignup").on('click', function()
{
var errorMsg = "";
$.when(nameExists())
.then(function(nameError)
{
if(nameError){errorMsg += nameError;}
return pwdsMatch();
})
.then(function(pwdError)
{
if(pwdError){errorMsg += pwdError;}
return emailValid();
})
.then(function(emailError)
{
if(emailError){errorMsg += emailError;}
return inputsFilled();
})
.then(function(inputsError)
{
if(inputsError){errorMsg += inputsError;}
})
.then(function()
{
if (errorMsg){alert(errorMsg);}
else {return addUser();}
})
.then(function(success)
{
success = Number(success);
if (success > 0)
{
alert("successfully added: "+success);
$.post("setSessionPHP.php",
{
loggedIn: true, userName: $("#userName").val()
},
function()
{
window.location.href = "index.php";
});
}
else if(!errorMsg){alert("Failed to add user. "+success);}
});
});
});
function nameExists()
{
return $.ajax({
type: "POST",
dataType: "json",
url: "data-out.php",
data: { submitSignup: 1, userName: $("#userName").val() }
}).then(function(data) {
if (parseInt(data) === 1) {
return "Username is already taken. ";
}
return null;
}).fail(function(jqXHR, textStatus, errorThrown) {
return 'Ajax Error [nameExists()]: ' + errorThrown;
});
}
function pwdsMatch()
{
var pwd = $("#pwd").val();
var pwdConfirm = $("#pwdConfirm").val();
if (pwd !== pwdConfirm)
{
pwdError = "Passwords do not match. ";
return pwdError;
}
}
function emailValid()
{
var emailError = "";
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; // simple email validation pattern
if (!emailPattern.test($("#email").val().trim()))
{
emailError = "The email is not in a valid email format. ";
}
return emailError;
}
function inputsFilled()
{
var inputsError = "";
var anyEmpty = false;
$(".input").each(function()
{
if ($(this).val().trim() === "")
{
anyEmpty = true;
}
});
if (anyEmpty === true)
{
inputsError = "Not all of the inputs are filled in. ";
}
return inputsError;
}
function addUser()
{
return $.ajax({
type: "POST",
dataType: "json",
url: "data-out.php",
data: {
addUser: 1,
userName: $("#userName").val(),
email: $("#email").val(),
pwd: $("#pwd").val()
},
success: function(data) {
alert("ajax: "+data);
return data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Status: ", textStatus);
console.log("Error: ", errorThrown);
console.log("Response: ", jqXHR.responseText);
alert("AJAX Error [ addUser() ] :" + "Status: " + textStatus + " Error: " + errorThrown + " Response: " + jqXHR.responseText);
$("#error").text("AJAX Error [ addUser() ] :" + "Status: " + textStatus + " Error: " + errorThrown + " Response: " + jqXHR.responseText);
}
});
}
</script>
</body>
</html>
data-out.php 代码:
<?php
// STARTS SESSION FOR THIS PAGE
session_start();
header('Content-Type: application/json');
// CONNECTS TO DATABASE
include 'connection.php';
$submitSignup = isset($_POST['submitSignup']) ? $_POST['submitSignup'] : null;
$userName = isset($_POST['userName']) ? $_POST['userName'] : null;
if($submitSignup){
$data = array();
$findme = "SELECT * FROM users WHERE username = '{$userName}'";
$foundme = mysqli_query($connect, $findme);
$countme = mysqli_num_rows($foundme);
if($countme>0)
{
array_push($data, 1);
print json_encode($data);
} else
{
array_push($data, 0);
print json_encode($data);
}
} else {
header("location: ../proj_login/data-in.php");
}
$addUser = isset($_POST['addUser']) ? $_POST['addUser'] : null;
if ($addUser)
{
$data = array();
$username = mysqli_real_escape_string($connect, $_POST['userName']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$pwdhashed = password_hash(mysqli_real_escape_string($connect, $_POST["pwd"]).$username, PASSWORD_DEFAULT);
$createUser = "INSERT INTO users(username, email, pwd, perms) VALUES('$username', '$email', '$pwdhashed', '0')";
if (mysqli_query($connect, $createUser))
{
$last_id = mysqli_insert_id($connect);
array_push($data, $last_id);
print json_encode($data);
} else {
print json_encode(['success' => false, 'error' => 'Failed to insert user: ' . mysqli_error($connect)]);
}
}
终于弄清楚了(自然是在发布我的问题几分钟后)。问题出在 data-out.php 中的这段代码:
} else {
header("location: ../proj_login/data-in.php");
}
我最初把它放在那里是为了如果有人访问 data-out.php 而不通过 data-in.php 则重定向到正确的用户页面。当我向 data-out.php 添加更多功能时,这行代码把事情搞砸了,因为触发标头重定向的条件没有考虑到新代码。
哇,这确实是一个很奇怪的事情,但不一定是......也许有一天这会对某人有所帮助......