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