javascript - $this->request->is ('ajax' ) 始终为 false

标签 javascript php jquery ajax cakephp

我的 View 中有代码,但是通过 ajax 发送到我的 Controller 操作(如 add.ctp 的最后一部分所示)

//add.ctp
 <?php
  echo $this->Form->create('Poll',array('action' => 'index'));
  echo $this->Form->input('one', array('id'=>'name'));
  echo $this->Form->input('two', array('id'=>'email'));
  echo $this->Form->input('three', array('id'=>'message'));
  echo $this->Form->input('four', array('id'=>'four'));


 echo $this->Js->submit('Send', array('id' => 'btn'), array(
 'before'=>$this->Js->get('#sending')->effect('fadeIn'),
 'success'=>$this->Js->get('#sending')->effect('fadeOut'),
 'update'=>'#success'
  )); 
  echo $this->Form->end();
  ?>

<div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>
<script>



 $('#btn').click(function(event) {

 form = $("#PollIndexForm").serialize();

  // console.log(form);
 $.ajax({
   type: "POST",
   url: 'pollsController/index';,
   data: form,

   success: function(data){
      //
   }

 });

 event.preventDefault();
// return false;  //stop the actual form post !important!

});

</script>

在到达我的 Controller 时,我做了一个 isAjax 请求测试,如果失败了

public $components = array('RequestHandler');

public function index(){ 
$this->autoRender = false;

      if($this->RequestHandler->isAjax()){
    echo debug('Ajax call');

       }
     if(!empty($this->data)){
       echo debug('not empty');
      }
}

每次我尝试运行它时我都得到“不为空”并且 $this->request->is('ajax') 总是错误的 我的 cakephp 版本是 2.3,我已经尝试过 $this->request->is('ajax') 等等。 如果有人能指出我遗漏了什么,我将不胜感激

最佳答案

在你的代码中,你有

if($this->RequestHandler->isAjax()){

尝试以这种方式制作条件:

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

}

http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html?highlight=isajax#requesthandlercomponent

RequestHandlerComponent: Many of RequestHandlerComponent’s methods are just proxies for CakeRequest methods. The following methods have been deprecated and will be removed in future versions: isSsl() isAjax() isPost() isPut() isFlash() isDelete() getReferer()getClientIp()

关于javascript - $this->request->is ('ajax' ) 始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21955304/

相关文章:

jquery - 以 $(this) 目标的选择器开始

javascript - 在 jQuery UI 对话框上启动 TinyMce

javascript - JQuery:如何在html元素<b></b>中创建单词列表?

javascript - 加载小书签时未捕获的 ReferenceError

javascript - Slick JS 作为滑动选项卡

Postman 中的 Php 连接文件错误

javascript - JS在动画中断后获取元素位置

javascript - 在 Protractor 中获取元素属性值

php - 从字符串中获取电子邮件 - 正则表达式语法 + preg_match_all

PHP SQL 获取查询中的下一行(带有用户订购的结果)