gpt4 book ai didi

javascript - AJAX 成功或错误未触发

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

我似乎无法弄清楚为什么这不起作用或找到相关文章。我可以看到 firebug 中的 json 对象从 post 请求返回 success: false 或 success: true,所以我不知道为什么该函数不会触发。

ajax

$("#login").submit(function (e) {
e.preventDefault();

$.ajax({
url: "../process/login-process.php",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { 'username': $('[name=username]').val(), 'password': $('[name=password]').val() },
beforeSend : function (){
//$("#login").hide();
},
success: function(data){
window.localation=data.redirect;
},
error: function(data) {
$(".error").html('');
alert('wtf');
if(data.empty) {
$(".error").html(data.empty);
}
if(data.incorrect) {
$(".error").html(data.incorrect);
}
}
});
});

php

<?php 
session_start();
include "../inc/connect.php";
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$password = hash('sha256', $password);
$sql = "SELECT * FROM admin WHERE username ='$username' AND password ='$password'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_array($result);
$count=mysqli_num_rows($result);
if ($username == "" || $password == "") {
$data['empty'] = 'All fields are required.';
} else if(($count==1) && ($username)) {
$_SESSION['user'] = $row['firstName'];
$_SESSION['userID'] = $row['adminID'];
$data['success'] = true;
$data['redirect'] = '../pages/dashboard.php';
} else {
$data['success'] = false;
$data['incorrect'] = "Incorrect Username or Password.";
}
echo json_encode($data);
?>

最佳答案

您需要在代码中更正两件事,

  1. success 回调中将 window.localation 更改为 window.location
  2. 在ajax请求中添加dataType: 'JSON'或在成功回调中使用$.parseJSON

因此,您的成功回调应该是:

success: function(data){
data = $.parseJSON(data); // <- Don't use this if you add dataType: 'JSON' in ajax
window.location=data.redirect; //<- Spelling corrected for location
}

关于javascript - AJAX 成功或错误未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882171/

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