首页 > 解决方案 > 使用 Sweetalert 单击“确定”后重新加载页面

问题描述

在成功消息后尝试重新加载页面,但它没有重新加载..

我有这个代码

$.ajax({
  type: "post",
  url: '/action.cfm?method=quote',
  data: datastring,
  success: function(data) {
    var valid = $.trim(data);
    if (valid.toLowerCase().indexOf("error") == '-1') {
      localStorage.setItem("swal", swal({
        title: "Good job!",
        text: 'Thanks',
        type: "success",
        showConfirmButton: true
      }).then(function() {
        location.reload();
      }));
      localStorage.getItem("swal");
    } else {
      swal("Oops", data, "error");
    }
  }
});

但我对此有误

(index):389 Uncaught TypeError: Cannot read property 'then' of undefined
    at Object.success ((index):389)
    at fire (jquery-1.12.4.js:3232)
    at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362)
    at done (jquery-1.12.4.js:9840)
    at XMLHttpRequest.callback (jquery-1.12.4.js:10311)

标签: javascriptjquerysweetalert2

解决方案


确保您使用的是新版本的 Sweetalert(下面,在 jsfiddle 中,您可以找到 2.1.2) - 我收到了关于使用 deprecatedshowConfirmButtontypeproperties 的警告。这是在 jsfiddle 中工作的稍作修改的代码:

$(document).ready(function() {
    $.ajax({
        type: "post",
        url: '/echo/json/',
        data: {},
        success: function(data) {
            var valid = $.trim(data);
            if (valid.toLowerCase().indexOf("error") == '-1') {
                localStorage.setItem("swal", swal({
                    title: "Good job!",
                    text: 'Thanks',
                    icon: "success",
                    button: true
                }).then(function() {
                    console.log('sth');
                    location.reload();
                }));
                localStorage.getItem("swal");
            } else {
                swal("Oops", data, "error");
            }
        }
    });
});

https://jsfiddle.net/wlecki/rwc58h17/

但总的来说,如果你必须将它存储在浏览器的本地存储中,我建议你只在那里存储一个 sweetalert 选项,如果你想显示一个 sweetalert 就使用它们:

$(document).ready(function() {
    $.ajax({
            type: "post",
            url: '/echo/json/',
            data: {},
            success: function(data) {
                var valid = $.trim(data);
                if (valid.toLowerCase().indexOf("error") == '-1') {
                    localStorage.setItem("swal", JSON.stringify({
                        title: "Good job!",
                        text: 'Thanks',
                        icon: "success",
                        button: true
                    }));

                    swal(JSON.parse(localStorage.getItem("swal"))).then(() => location.reload());
            } else {
                swal("Oops", data, "error");
            }
        }
    });
});

https://jsfiddle.net/wlecki/71vzasxh/


推荐阅读