SweetAlert 中使用 PHP 变量的自定义消息

发布于 2025-01-12 19:28:51 字数 1429 浏览 0 评论 0原文

我想使用 PHP 文件中的返回变量来显示 SweetAlert 中可能出现错误的自定义消息。有可能吗?

输入图片此处描述

文件 PHP:

if ($a > $b) {
    echo "true";
    $msg = "First personalised message";
    exit;
} elseif ($a == $b) {
    echo "true";
    $msg = "Second personalised message";
    exit;
} else {
    echo "false";
    exit;
}

JAVASCRIPT 代码:

$(document).ready(function ($) {
    $('#moving_send_toners').on('submit',function(e) {
        if ($("#moving_send_toners").valid()) {
            $.ajax({
                url:'action_send_toners.php',
                data:$(this).serialize(),
                type:'POST',
                success:function(data){
                    if (data == 'false') {
                        console.log(data);
                        swal('Sucesso!', 'Ação realizada.', 'success');
                        $('#moving_send_toners')[0].reset();
                    }
                    if (data == 'true') {
                        swal('Ops!', "Toner não pode ser enviado :(", "error");
                    }
                },
                error:function(data){
                    swal("ERRO!", data.msg, "error");
                }
            });
        }
        e.preventDefault();
    })
});

I would like to use a return variable from my PHP file to display a custom message of possible errors in SweetAlert. It is possible?

enter image description here

File PHP:

if ($a > $b) {
    echo "true";
    $msg = "First personalised message";
    exit;
} elseif ($a == $b) {
    echo "true";
    $msg = "Second personalised message";
    exit;
} else {
    echo "false";
    exit;
}

JAVASCRIPT CODE:

$(document).ready(function ($) {
    $('#moving_send_toners').on('submit',function(e) {
        if ($("#moving_send_toners").valid()) {
            $.ajax({
                url:'action_send_toners.php',
                data:$(this).serialize(),
                type:'POST',
                success:function(data){
                    if (data == 'false') {
                        console.log(data);
                        swal('Sucesso!', 'Ação realizada.', 'success');
                        $('#moving_send_toners')[0].reset();
                    }
                    if (data == 'true') {
                        swal('Ops!', "Toner não pode ser enviado :(", "error");
                    }
                },
                error:function(data){
                    swal("ERRO!", data.msg, "error");
                }
            });
        }
        e.preventDefault();
    })
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

此岸叶落 2025-01-19 19:28:51

从您包含的图像来看,您似乎想在 .error() 回调中使用 PHP 的响应,而不是 .success () 回调(这是使用后端响应的通常方式)。

当请求失败时,会触发 .error() 回调。 来自文档

错误
请求失败时调用的函数。该函数接收三个参数:...第二个参数(除了 null 之外)的可能值为“timeout”、“error”、“abort”和“parsererror”。当发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。

所以你可以看到这个回调处理的错误类型是 404 错误、500 服务器错误、网络超时等。对于这种错误,你的 PHP 没有运行。此处理程序仅在 PHP 未运行时才会触发,因此无法从 PHP 向其传递消息。

如果您确实想在您的成功处理程序中使用该消息,请按以下方法操作。首先在 PHP 中:

if ($a > $b) {
    $response = [
        'status'    => true,
        'message'   => 'First personalised message'
    ];
    
} elseif ($a == $b) {
    $response = [
        'status'    => true,
        'message'   => 'Second personalised message'
    ];

} else {
    $response = [
        'status'    => false,
        'message'   => ':-('
    ];
}

header('Content-Type: application/json');
echo json_encode($response);
exit;

然后在 Javascript 中使用返回的 JSON:

success: function(response) {
    console.dir(response);
    
    if (response.status === false) {
        swal('Sucesso!', response.message, 'success');
        $('#moving_send_toners')[0].reset();
        
    } else {
        swal('Ops!', response.message, "error");
        
    }
},

From the image you included, it looks like you want to use the response from your PHP in the .error() callback, not the .success() callback (as is the usual way back-end responses are used).

The .error() callback is fired when the request fails. From the docs:

error.
A function to be called if the request fails. The function receives three arguments: ... Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

So you can see the type of error that this callback handles are things like 404 errors, 500 server errors, network timeouts, etc. For that kind of error, your PHP did not run. This handler only ever fires when your PHP did not run, so there is no way to pass a message to it from your PHP.

If you actually want to use the message in your success handler, here's how you would do that. First in your PHP:

if ($a > $b) {
    $response = [
        'status'    => true,
        'message'   => 'First personalised message'
    ];
    
} elseif ($a == $b) {
    $response = [
        'status'    => true,
        'message'   => 'Second personalised message'
    ];

} else {
    $response = [
        'status'    => false,
        'message'   => ':-('
    ];
}

header('Content-Type: application/json');
echo json_encode($response);
exit;

Then use that returned JSON in your Javascript:

success: function(response) {
    console.dir(response);
    
    if (response.status === false) {
        swal('Sucesso!', response.message, 'success');
        $('#moving_send_toners')[0].reset();
        
    } else {
        swal('Ops!', response.message, "error");
        
    }
},
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文