[英]Return http response code from PHP to AJAX
我正在嘗試為網站創建登錄頁面。 我有一個使用AJAX向PHP腳本發送請求以檢查是否輸入了正確的用戶名和密碼的函數。如果查詢返回成功的結果,則發送http_response_code(200),否則,我發送http_response_code(403) 。 但是,登錄功能似乎未返回任何響應狀態。 響應似乎不確定。 在這種情況下,即使輸入了正確的密碼和用戶名,該功能也會給我窗口提示輸入錯誤的密碼或用戶名。 我應該檢查什么條件才能根據http響應代碼確定成功函數應該做什么? 還有另一種方法可以根據PHP腳本的作用將條件返回給AJAX?
這里是登錄功能的代碼。
function login(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'username1=' + username + '&password1=' + password;
if (username == '' || login == ''){
window.alert("Please fill in username or password.");
}
else{
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
crossDomain : true,
success: function(response) {
if (response.status == 200) {
window.location = 'http://localhost/site.html';
}
else {
window.alert("The password or username you have entered is not valid");
}
}
});
}
return false;
}
這是我的PHP腳本。
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
session_start();
$_SESSION['username'] = $username2;
http_response_code(200);
echo "Successful Login";
exit;
}
else{
http_response_code(403);
echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>
當您檢查的響應和發送GET response.status
你實際上並不有一個數組或對象在你手中的回應:
因此,在檢查登錄名時,您可以創建一個包含status
和message
的數組,並使用json_encode()
創建一個數組,以便您的JavaScript代碼可以選擇它並讀取它。
<?php
// fix your query connection - you are currently vulnerable. It does go outside of the scope of your question so I am not going to tackle it here.
if(!empty($row['username']) AND !empty($row['password'])) {
session_start();
$_SESSION['username'] = $username2;
$return = array(
'status' => 200,
'message' => "Login Successful."
);
http_response_code(200);
}
else{
$return = array(
'status' => 403,
'message' => "Login attempt denied."
);
http_response_code(403);
}
print_r(json_encode($return));
現在,您可以在AJAX函數中獲取響應:
success: function(response) {
var data = $.parseJSON(response);
if (data.status == 200) {
window.location = 'http://localhost/site.html';
}
else {
window.alert(data.message);
}
}
成功函數中使用的response
參數是AJAX調用返回的數據,而不是狀態和/或標題。 您可以通過獲取函數的第二個參數來獲取描述狀態的字符串:
$.ajax({
...
success: function(data, status){
if(status == "success"){
// success code.
}
}
});
查看jQuery.ajax文檔以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.