【问题标题】:Simple success/error return with ajax and php使用 ajax 和 php 的简单成功/错误返回
【发布时间】:2013-12-06 06:20:08
【问题描述】:

刚开始学习 ajax,虽然我在尝试在数组中返回成功消息时遇到了麻烦。

<script type="text/javascript">
$(function () {
    $('#delete').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize()
        }).done(function (response) {
            if (response.success) {
                alert('Saved!');
            } else {
                alert('Some error occurred.');
            }
        });
    });
});
</script>

<?php
$array = array();
$array['success'] = TRUE;
echo $array;
?>

response.success 应该引用 $array['success'] 对吗?

【问题讨论】:

  • 检查您的控制台网络选项卡并查看该请求的状态。

标签: php jquery ajax


【解决方案1】:

您正在尝试回显您的数组,它只会吐出“Array”。

相反,您需要将数组编码为 JSON 并将其回显。

改变这个:

echo $array;

到这里:

echo json_encode($array);

您可能还需要在 ajax 参数中添加您的 dataType,以便 jQuery 自动解析响应:

dataType : 'json' // stick this after "data: $form.serialize()" for example

另外,这里有一篇很好的文章,可以阅读如何正确处理 ajax 调用的成功/错误(感谢@Shawn):

Jquery checking success of ajax post

【讨论】:

  • @Shawn 该答案推荐 successerror 从 jQuery 1.8 开始已被弃用。
  • @jszobody 不,不推荐使用成功和错误选项。不推荐使用成功和错误方法。两种完全不同的东西。
  • @KevinB 你说得对,我误读了另一个答案。会更新。
  • @user756659 这有帮助吗?您的问题解决了吗?
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多