Sweetalert2 Ajax - 发布输入数据

Kra*_*ray 4 javascript ajax jquery sweetalert2

我最近在我的项目中与 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>
Run Code Online (Sandbox Code Playgroud)

我想要完成的,并且有一个困难的时间是利用 ajax 从输入字段“textarea”发布数据。

我还想通过使用以下内容来验证提交是成功还是失败

'成功'

swal(
        "Sccess!",
        "Your note has been saved!",
        "success"
      )
Run Code Online (Sandbox Code Playgroud)

“失败的”

swal(
          "Internal Error",
          "Oops, your note was not saved."
          "error"
        )
Run Code Online (Sandbox Code Playgroud)

我还需要将一个 PHP 对象传递给 ajax(一个唯一的客户 ID 键),并允许 ajax 保存数据。

<?php $CustomerKey; ?>

Sweet Alert 没有提供太多关于如何使用 ajax 的文档,并且很难找到更多关于我的 stackoverflow 问题和在线搜索的信息。

任何帮助将不胜感激。

JSFiddle 示例;

https://jsfiddle.net/px0e3Lct/1/

Hay*_*ore 5

嗨,您需要做的是在 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"
    )
  }
})
Run Code Online (Sandbox Code Playgroud)

在这个例子中,要在你的 php 文件中获取 customerKey 值,它的(YourPhpFile.php) 只需包括

$CustomerKey = $_POST['CustomerKey'];

祝你好运