【问题标题】:How do I throw an error message within AJAX?如何在 AJAX 中抛出错误消息?
【发布时间】:2016-01-13 11:38:33
【问题描述】:

由于某种原因,我无法抛出错误消息来说明我的用户表中是否存在电子邮件。我知道因为 AJAX 是异步的,所以我不能在完整函数中使用 try 和 catch 错误消息。但是我试过把它拆分成函数,还是不行。

Try, Catch Function(我确实在我的代码中的其他地方调用它)

try {

    // Check fields are not empty
    if (!firstName || !lastName || !aquinasEmail || !sPassword || !sCPassword || !Gender) {
        throw "One or more field(s) have been left empty.";
    }

    // Check the email format is '@aquinas.ac.uk'
    if(!emailCheck.test(aquinasEmail)) {
        throw "The email address you entered has an incorrect email prefix. ";
    }

    // Check there are not any numbers in the First or Last name
    if (!regx.test(firstName) || !regx.test(lastName)) {
        throw "First Name or Last Name is invalid.";
    }

    // Check the confirmation password is the same as the first password
    if (sPassword != sCPassword) {
        throw "The two passwords you've entered are different.";
    }

    if(duplicatedEmail()) {
        throw "Sadly, your desired email is taken. If you have forgotten your password please, <a href=\"#\">Click Here</a>";
    }



} catch(err) {
    if (!error) {
        $('body').prepend("<div class=\"error alert\">"+err+"</div>");
        $('.signupInput.sPassword').val('');
        $('.signupInput.sCPassword').val('');
        setTimeout(function() {
            $('.error.alert').fadeOut('1000', function() {$('.error.alert').remove();});
        }, 2600);
    }

    event.preventDefault();
}

AJAX 功能:

function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
        $.ajax({
            type: "POST",
            url: "/login/ajaxfunc/verifyReg.php",
            dataType: "JSON",
            async: false,
            data: $('.signupForm').serialize(),
            success: function(data) {
                    if (data.emailTaken == true) {
                        return true;
                    } else {
                        return false;
                    }
            }
        });
}

verifyReg.php

<?php
    header('Content-Type: application/json', true);
    $error = array();
    require_once '../global.php';

    $_POST['aquinas-email'] = "aq142647@aquinas.ac.uk";

    // Check if an email already exists.
    $checkEmails = $db->query("SELECT * FROM users WHERE aquinasEmail = '{$_POST['aquinas-email']}'");
    if ($db->num($checkEmails) > 0) {
        $error['emailTaken'] = true;
    } else {
        $error['emailTaken'] = false;
    }

    echo json_encode($error);
?>

【问题讨论】:

  • 你到底想达到什么目的?你想在 AJAX 调用出错时抛出异常?
  • 我想检查输入的电子邮件是否存在。
  • 看看这个answer它可以帮助你:
  • 同步请求是一种不好的做法。

标签: javascript jquery ajax try-catch


【解决方案1】:

使用 jquery ajax 函数处理错误添加这样的错误回调

           function duplicatedEmail() {
            // Use AJAX function to do verification checks which can not be done via jQuery.
                    $.ajax({
                        type: "POST",
                        url: "/login/ajaxfunc/verifyReg.php",
                        dataType: "JSON",
                        async: false,
                        data: $('.signupForm').serialize(),
                        success: function(data) {
                                if (data.emailTaken == true) {
                                    return true;
                                } else {
                                    return false;
                                }
                        },  
                       error: function() {
                             //Your Error Message   
                     console.log("error received from server");       
                               }  
                    });
            }

在你的 PHP 中抛出异常:

           throw new Exception("Something bad happened");

【讨论】:

    【解决方案2】:

    查看您的 AJAX 函数,以及这两个答案 herehere,您需要对返回同步结果的方式进行一些小改动:-

    function duplicatedEmail() {
    
        var result;
    
        $.ajax({
            type: "POST",
            url: "/login/ajaxfunc/verifyReg.php",
            dataType: "JSON",
            async: false,
            data: $('.signupForm').serialize(),
            success: function(data) {
                    result = data.emailTaken;
            }
        });
    
        return result;
    }
    

    【讨论】:

      【解决方案3】:

      使用ajax错误函数..

      function duplicatedEmail() {
      // Use AJAX function to do verification checks which can not be done via jQuery.
          $.ajax({
              type: "POST",
              url: "/login/ajaxfunc/verifyReg.php",
              dataType: "JSON",
              async: false,
              data: $('.signupForm').serialize(),
              success: function(data) {
                      if (data.emailTaken == true) {
                          return true;
                      } else {
                          return false;
                      }
              },
              error: function (result) {
                  alert("Error with AJAX callback"); //your message
              }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-04
        • 2017-11-26
        • 1970-01-01
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多