Cakephp - 返回AJAX成功响应的正确方法?

时间:2013-06-26 04:40:53

标签: ajax cakephp

我一直在使用以下技巧通过AJAX返回成功响应:

//In controller
echo 'success';

//In Javascript
if(response == 'success'){
    //redirect
    window.location.href = '/users/profile/';
}

它在localhost上运行正常。但是在Web服务器中,每次我想在成功后重定向页面时都会出现以下错误:

Cannot modify header information - headers already sent by (output started at ...

所以是的,我知道它是由重定向前的echo引起的。

那么,有没有正确的方法来回复成功回应?无需成为消息,只需truefalse即可。

[编辑]

使用exit('success'),它运行正常,但这是最好的方法吗?

感谢。

1 个答案:

答案 0 :(得分:2)

最好从javascript重定向。

//In controller
echo 'success'; exit;

//In Javascript
if(response == 'success'){
    window.location = 'your-controller-action';
}

修改

您可能有空格before/after php Opening/Closing tags in controller and models。在打开标签之前,从所有控制器和模型以及任何空格中删除所有结束标签。然后检查结果。