刚开始学习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']正确吗?
答案 0 :(得分:5)
您正在尝试回显您的数组,这只会吐出“数组”。
相反,您需要将数组编码为JSON并将其回显。
改变这个:
echo $array;
对此:
echo json_encode($array);
此外,您可能需要在ajax params中添加dataType
,以便jQuery自动解析响应:
dataType : 'json' // stick this after "data: $form.serialize()" for example
另外,这里有一篇很好的文章,介绍如何使用ajax调用正确处理成功/错误(感谢@Shawn):