【问题标题】:Can't get sweetalert2 ajax to work无法让 sweetalert2 ajax 工作
【发布时间】:2018-07-23 12:25:41
【问题描述】:

我对 ajax 有疑问,我正在努力学习它,但他不想要我 :)

这是我的代码:

<script>
    $('._givePP').on('click', () => {
        swal.mixin({
            input: 'text',
            confirmButtonText: 'Next &rarr;',
            showCancelButton: true,
            progressSteps: ['1', '2']
        }).queue([
            {
                title: 'Question 1',
                text: 'Chaining swal2 modals is easy'
            },
            {
                title: 'Question 2',
                text: 'bla bla 2'
            }
        ]).then((result) => {
            if (result.value) {
                $.ajax({
                    _dapepe: true,
                    url: '<?php echo Config::$data->url;?>action/profile', 
                    type: 'POST',
                    success: (e) => {
                        e = JSON.parse(e);
                        swal({
                            title: e.title,
                            text: e.message,
                            type: e.type
                        });
                    }
                });
            }
        })
    });
</script>

这是 php 代码:

<?php 
if(isset($_POST['_dapepe'])) {
    return print_r(json_encode(array('title' => 'Success','text' => 'gg','type' =>'success')));
}
?>

我想要得到的只是一个简单的 gg 文本,所以我知道它正在读取 php 文件,但我没有收到 gg 消息。有谁知道出了什么问题或为什么它不读取文本?

顺便说一句,我验证了它的工作网址。

【问题讨论】:

  • 另外,$('._givePP').on('click'... 应该真正包裹在 .ready... 因为它在静态父动态模式下不使用 .on

标签: php ajax sweetalert2


【解决方案1】:

您的 ajax 调用不会向服务器发送任何数据,因此 if(isset($_POST['_dapepe'])) 将永远不会是 true。这反过来意味着您的 PHP 代码永远不会返回任何数据,因此您的 JS “成功”代码将崩溃,因为它试图访问不存在的数据。尽管您没有提及,但您的浏览器控制台中可能有与此相关的错误或警告。

在 $.ajax 选项中,而不是

_dapepe: true,

你需要写

data: { _dapepe: true },

按照您编写的方式,jQuery 不知道您打算将 _dapepe 用作数据字段,它只是将其视为无法识别的选项,因此忽略了它。你需要把它放在data 选项中,这样 jQuery 就知道如何处理它了。

http://api.jquery.com/jquery.ajax/ 记录了您可以提供给 $.ajax() 方法的所有有效选项。

我也在你的 PHP 中推荐这些东西:

1) return print_r 是一个错误,不会起作用。 print_r 将其数据直接转储到输出,除非您将单独的标志设置为它的第二个参数(请参阅http://php.net/manual/en/function.print-r.php

2) 使用echo 而不是print_r - print_r 是一个调试工具。根据您返回的数据类型,它有时可能会打印实际上不属于您的变量数据的字符(例如https://eval.in/1040578)。在 json_encode() 的情况下它可能是安全的,但不要养成使用它的习惯。

2) 如果你的代码总是返回 something 会更好,即使它是一个空对象。如果根本没有响应数据,JavaScript 有时会崩溃。

考虑到这一点,我建议将 PHP 更改为:

<?php 
$array = array();

if(isset($_POST['_dapepe'])) {
    $array = array('title' => 'Success','text' => 'gg','type' =>'success');
}

echo json_encode($array, JSON_FORCE_OBJECT);
?>

【讨论】:

  • 谢谢你的回答,我没想到会有这样的回答。我按照您的所有步骤进行操作,现在可以了:)谢谢。
  • @AlexChristianSighireanu 没问题。如果答案对您有所帮助,请记得将其标记为“已接受”(单击问题旁边的勾号,使其变为绿色,请参阅stackoverflow.com/help/someone-answers) - 谢谢 :-)
  • @ADyson 我希望有人能从给出像你这样详细的答案中学习 ;-) 干杯
猜你喜欢
  • 1970-01-01
  • 2017-12-12
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多