我最近在我的项目中使用 SweetAlert2,我想整合一个“添加注释”功能。
用户点击一个按钮,被定向到一个页面,然后执行以下操作。
<script>swal({
title: "Add Note",
input: "textarea",
showCancelButton: true,
confirmButtonColor: "#1FAB45",
confirmButtonText: "Save",
cancelButtonText: "Cancel",
buttonsStyling: true
}).then(function () {
swal(
"Sccess!",
"Your note has been saved!",
"success"
)
}, function (dismiss) {
if (dismiss === "cancel") {
swal(
"Cancelled",
"Canceled Note",
"error"
)
}
})</script>
我正在尝试完成并遇到困难的是利用 ajax 从输入字段“textarea”发布数据。
我还想使用以下方法验证提交是成功还是失败
'成功'
swal(
"Sccess!",
"Your note has been saved!",
"success"
)
“失败”
swal(
"Internal Error",
"Oops, your note was not saved."
"error"
)
我还需要将一个 PHP 对象传递给 ajax(唯一的客户 ID key ),并允许 ajax 保存数据。
<?php $CustomerKey; ?>
Sweet Alert 没有提供太多关于如何使用 ajax 的文档,并且很难找到与我的 stackoverflow 问题和在线搜索有关的更多信息。
如有任何帮助,我们将不胜感激。
JSFiddle 示例;
最佳答案
您好,您需要做的是在 sweetalert 的 then 函数中调用 ajax,并使用 ajax 的数据参数将客户键变量作为 POST 变量传递。
var CustomerKey = 1234;//your customer key value.
swal({
title: "Add Note",
input: "textarea",
showCancelButton: true,
confirmButtonColor: "#1FAB45",
confirmButtonText: "Save",
cancelButtonText: "Cancel",
buttonsStyling: true
}).then(function () {
$.ajax({
type: "POST",
url: "YourPhpFile.php",
data: { 'CustomerKey': CustomerKey},
cache: false,
success: function(response) {
swal(
"Sccess!",
"Your note has been saved!",
"success"
)
},
failure: function (response) {
swal(
"Internal Error",
"Oops, your note was not saved.", // had a missing comma
"error"
)
}
});
},
function (dismiss) {
if (dismiss === "cancel") {
swal(
"Cancelled",
"Canceled Note",
"error"
)
}
})
在此示例中,为了在您的 php 文件中获取 customerKey 值,它的 (YourPhpFile.php) 只需包含
$CustomerKey = $_POST['CustomerKey'];
祝你好运
关于javascript - Sweetalert2 Ajax - 发布输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841570/