【问题标题】:Cake php 2x is not detecting ajax requestCake php 2x 未检测到 ajax 请求
【发布时间】:2016-07-28 05:34:30
【问题描述】:

我在一台服务器上有一个 api,在另一台服务器上查看文件。当我使用 ajax 请求时,

$this->request->is('ajax')

总是显示为假。但它在本地 xampp 服务器中运行良好。我还启用了请求服务器的来源。我应该怎么办。是不是因为跨域。

我的 ajax 是

$.ajax(
            {
                url:'http://12.34.567.890/Users/getu.json',
                // url:'<?php echo URL; ?>Users/getu.json',
                type:"POST",
                data:{access_token:'<?php echo $_SESSION["token"]->access_token; ?>', api_key:"***************"},
                async:false,
                success:function(res)
                {
                    console.log(res);
                }
            });

但是我发现主要问题是在实时服务器中时,ajax 请求没有标头

X-Requested-With:XMLHttpRequest;

所以,因此 cake 无法识别 ajax 请求。

【问题讨论】:

  • 您是否在控制器中使用 requesthandler 组件? public $components = array('RequestHandler');
  • 是的,我的 appController 中有它。

标签: php ajax cakephp


【解决方案1】:

您的问题可能出在您的 ajax 调用中。当您执行请求时,您使用的 dataType 是什么? 如果您需要进行跨域 ajax 调用,您必须在 ajax 调用中使用 JSONP 作为 dataType,如下所示:

$.ajax( {
   url: 'http://my_remote_server/controller/action',
   dataType: 'jsonp',
   success: function( res ) {
      // do stuff with res
      alert("Success");
   },
   error:function() {
      alert("Error");
   }
} );

然后在您的控制器->动作中使用以下内容来检测 ajax 请求:

if( $this->request->is( 'ajax' ) ) {
   // process the request and send output
}

【讨论】:

  • 我不需要将 dataType 包含为 jsonp,因为我已经允许请求域的访问源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 2014-05-29
  • 2013-10-18
  • 2015-08-08
  • 2012-04-17
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多