AJAX总是认为php返回成功,即使失败

我有一个添加新用户帐户的 php 脚本。addAccount() 的一部分检查用户名是否有效,如果无效,则返回不可用的异常(出现致命错误)。我的问题是 AJAX 将一切都解释为成功并无论如何都显示成功消息。如何解决此问题或至少捕获致命错误并显示正确的消息?


$(document).on('click', '#createUserBtn', function(e){

    e.preventDefault();

    $.ajax({

        url:'addUser.php',

        type:'post',

        data:$('#addUser').serialize(),

        success:function(){


                toastr.success("User successfully added!");

            },

        error: function(){

            toastr.warning('Uh-oh! Something went wrong with adding this user!');

        }

    });

});


添加用户.php


<?php

session_start();

/* Include the database connection file (remember to change the connection parameters) */

require './db_inc.php';


/* Include the Account class file */

require './account_class.php';


  $type = $_POST['type'];

  $username = $_POST['uname'];

  $password = $_POST['password'];

  $comp = $_POST['company'];

  $email = $_POST['email'];

  $fname = $_POST['fname'];

  $lname = $_POST['lname'];

  $query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");


$account = new Account();

// Will print all the values received.

    $newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);

    header('Location: ./dashboard.php?user='.$username);




?>


这是使用的 addAccount 函数...


    public function addAccount(string $name, string $passwd, string $comp, string $email, string $fname, string $lname, string $type): int

    {

        /* Global $pdo object */

        global $pdo;


        /* Trim the strings to remove extra spaces */

        $name = trim($name);

        $passwd = trim($passwd);


        /* Check if the user name is valid. If not, throw an exception */

        if (!$this->isNameValid($name))

        {

            throw new Exception('Invalid user name');

        }


        /* Check if the password is valid. If not, throw an exception */

        if (!$this->isPasswdValid($passwd))

        {

            throw new Exception('Invalid password');

        }



GCT1015
浏览 80回答 2
2回答

MYYA

首先,如果您从 javascript 请求某些内容,则无法通过 php 重定向用户,请从 addUser.php 中删除此行header('Location: ./dashboard.php?user='.$username);现在要将结果从 php 返回到客户端,您必须DIE使用带有值的 php,最好的方法是 JSON在 addUser.php 检查你想要什么并返回如下值:&nbsp; &nbsp; <?phpsession_start();/* Include the database connection file (remember to change the connection parameters) */require './db_inc.php';/* Include the Account class file */require './account_class.php';&nbsp; $type = $_POST['type'];&nbsp; $username = $_POST['uname'];&nbsp; $password = $_POST['password'];&nbsp; $comp = $_POST['company'];&nbsp; $email = $_POST['email'];&nbsp; $fname = $_POST['fname'];&nbsp; $lname = $_POST['lname'];&nbsp; $query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");$account = new Account();// Will print all the values received.&nbsp; &nbsp; $newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);&nbsp; &nbsp; &nbsp; &nbsp; if(intval($newId) > 0) // if user created&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die(json_encode(array('status' => 'ok')));&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die(json_encode(array('status' => 'error')));&nbsp; &nbsp; ?>然后更改您的客户端,如下所示:$(document).on('click', '#createUserBtn', function(e){&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url:'addUser.php',&nbsp; &nbsp; &nbsp; &nbsp; type:'post',&nbsp; &nbsp; &nbsp; &nbsp; data:$('#addUser').serialize(),&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json", // <- Add this line&nbsp; &nbsp; &nbsp; &nbsp; success:function(response){ // <- add response parameter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Here check result&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(response['status'] == 'ok')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toastr.success("User successfully added!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toastr.warning('Uh-oh! Something went wrong with adding this user!');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function(){&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; statusCode: { // <- Add this property&nbsp; &nbsp; &nbsp; &nbsp; 500: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;toastr.warning('Uh-oh! Something went wrong with adding this user!');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; });});

慕桂英546537

您可以使用http_response_code()返回 HTTP 错误代码(通常代码 500 :内部服务器错误)。您可以使用 try/catch 块来做到这一点:try{&nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp;$account = new Account();&nbsp; &nbsp; &nbsp;// Will print all the values received.&nbsp; &nbsp; &nbsp;$newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);&nbsp; &nbsp; &nbsp;header('Location: ./dashboard.php?user='.$username);}catch(Exception $e){&nbsp; &nbsp; http_response_code(500);&nbsp; &nbsp; exit();}
打开App,查看更多内容
随时随地看视频慕课网APP