我目前正在创建一个移动应用程序。我使用 cakephp2.0 作为后端来处理请求和响应。我希望 cakephp 处理请求并将 json 响应发送回移动应用程序(应用程序工艺)。
(1) 对于用户 Controller ,我这样做了:
public function index() {
$this->autoRender = false;
return new CakeResponse(array('body' => json_encode($this->User->find('all'))));
}
(2) AppController 我这样做了:
var $components = array('RequestHandler');
function beforeFilter() {
if ( $this->RequestHandler->isAjax() ) {
Configure::write ( 'debug', 0 );
}
}
(3) 我创建了一个不在 cakePHP 文件夹中的单独的 html 文件来测试 json 响应:
<body>
<a href="">jQuery</a>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "get",
url: "http://localhost/jungle/users",
success: function(response){
alert(response);
}
});
});
</script>
</body>
当我打开(3)中提到的html文件时,我没有从cakephp后端得到任何响应。我尝试使用 firebug,但也没有显示任何响应。
但是,当我尝试从浏览器访问 cakephp 用户索引页面时,json 很好地显示出来:
[{"User":{"id":"1","name":"John","mobile_code":"+65","mobile number":"901111234"}}]
有人可以帮助我吗?
最佳答案
您的设置没有任何问题。我知道这听起来很愚蠢,但是您是否在测试 HTML 中正确包含了 jQuery,并且它是否成功触发了请求?
要验证的另一件事是您在哪里托管测试 HTML 文件?它是由网络服务器提供的还是只是位于您的桌面上?如果没有提供服务,则 javascript 很可能被禁用且未运行。
顺便说一句,isAjax
is deprecated in CakePHP 2.相反,请使用 this->request->is( 'ajax' )
来测试 Ajax。但这应该不会影响您的问题。
关于php - Cakephp作为移动网站的后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9486959/