php - 检查ajax请求的失败和成功

标签 php javascript jquery ajax

我已经向我的login.php 文件写入了一个ajax post 请求,该请求会回显“错误”或“成功”等内容。

我不太确定如何使用这个函数,因为我也想检查失败和其他内容,然后将文本添加到错误框中。

有什么想法吗?

这是我当前的代码:

$('#submit').click( function() {
    $.ajax({
        url: 'login.php',
        type: 'post',
        dataType: 'json',
        data: $('form#loginForm').serialize(),
        beforeSend:function(){
            launchPreloader();
        },
        complete:function(){
            stopPreloader();
        },
        success: function(data) {
            window.href("chat.php");
        }
    });
});

最佳答案

来自jQuery $.ajax() documentation ...

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

以您的代码为例......

$('#submit').click( function() {
    $.ajax({
        url: 'login.php',
        type: 'post',
        dataType: 'json',
        data: $('form#loginForm').serialize(),
        beforeSend:function(){
            launchPreloader();
        },
        complete:function(){
            stopPreloader();
        },
        success: function(data) {
            window.href("chat.php");
        }
    }).done(function() {
        alert('Done!');
    }).fail(function() {
        alert('Fail!');
    });
});

关于php - 检查ajax请求的失败和成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18191760/

相关文章:

php - php/mysql存储海量数据复杂关系的最佳方式

heroku - 无法安装therubyracer,报错

jquery - 按标签和用户名过滤 Instagram api 结果

php - 从一个数据库读取数据并使用 PHP 插入另一个数据库时出现编码错误

php - PDO Informix ODBC 驱动程序可与 PHP CLI 一起使用,但不能在浏览器中使用

php - 日期范围查询忽略跨越年末和年初的月份

javascript - 在 JavaScript 中处理单击和拖动事件

javascript - 当 Google 文档中的所有文件时 HTML 无法加载图像

javascript - 用 jquery 分配一个 javascript 变量只需要执行一次?

jQuery GET 到同一域上的 API 会出现 CORS 错误