【问题标题】:How to catch error from sweet alert ajax function?如何从甜蜜警报 ajax 函数中捕获错误?
【发布时间】:2022-02-01 18:36:47
【问题描述】:

经过多次搜索后,我在甜蜜警报中找不到解决问题的方法。 当 ajax 发送特定消息时,我需要向用户显示专门的错误消息。

我的功能:

function fadd() {    
      Swal.fire({
title: 'do you want to save?',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {

$.ajax({
    type: "POST",
    url: "ajaxfile.php",
success: function(){ 
                  console.log(response['abc']);
                   }

})
  }
})
}

关于 ajax (ajaxfile.php) 我有:

if($sqlcr->num_rows === 0) {
    $insql=mysql_query("INSERT INTO table (item) VALUES('".$cont."','".$tp."','".$usercode."')");
mysql_query($insql);    

 return response(json_encode(array("abc"=>'ok')));
} 
else {
    return response(json_encode(array("abc"=>'failed')));
}
}

问题是我无法从函数中捕获 json 消息“失败”...

我在网上找到了一些示例代码,但缺少的部分是 ajax 配置文件,可能那里有问题...

对此有什么帮助吗? 提前致谢

【问题讨论】:

    标签: php json ajax sweetalert


    【解决方案1】:

    这都是关于响应头的。如果请求失败,您通常不会返回 HTTP 200 OK,因为如果出现问题,响应不应该是 OK。下面是一个简短的示例,如何使用 HTTP 标头来表示出现问题。

    <?php
    declare(strict_types=1);
    namespace Marcel;
    
    $failure = true;
    
    // everything is fine - send a http 200
    if ($failure === false) {
        header('HTTP/1.1 200 OK');
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([ 'test' => 'ok' ]);
        exit();
    }
    
    if ($failure === true) {
        header('HTTP/1.1 422 Unprocessable Entity');
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([ 'test' => 'not ok' ]);
        exit();
    }
    

    您可以找到http状态码here的完整列表。

    由于我们在响应中有一个状态码,我们可以用你的 jQuery sn-p 来处理这个问题,因为不在 200 范围内的所有东西都不好,我们可以使用 jQuery 的 async 的 error 函数请求。

    jQuery.ajax({
        type: 'POST',
        url: 'ajaxfile.php',
        success: (response) => {
            console.log(response);
        },
        error: (request, status, error) => {
            console.log(request);
        }
    });
    

    因为 jQuery 知道何时抛出错误的 http 状态代码。

    【讨论】:

    • 一个小提示:不要再使用 mysql_* 函数了。它们已经过时多年,不适用于当前的 PHP 版本。
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2017-12-11
    相关资源
    最近更新 更多