SweetAlert 中使用 PHP 变量的自定义消息
我想使用 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?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您包含的图像来看,您似乎想在
.error()
回调中使用 PHP 的响应,而不是.success ()
回调(这是使用后端响应的通常方式)。当请求失败时,会触发
.error()
回调。 来自文档:所以你可以看到这个回调处理的错误类型是 404 错误、500 服务器错误、网络超时等。对于这种错误,你的 PHP 没有运行。此处理程序仅在 PHP 未运行时才会触发,因此无法从 PHP 向其传递消息。
如果您确实想在您的成功处理程序中使用该消息,请按以下方法操作。首先在 PHP 中:
然后在 Javascript 中使用返回的 JSON:
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: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:
Then use that returned JSON in your Javascript: