2014-02-22 64 views
1

我在我的视图中有代码,但通过ajax发送给我的控制器动作(如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> 
在得到我的控制器

,我做了一个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')和所有。 什么,我错过了

+0

你能尝试打开开发者控制台或萤火虫或一些调试工具,并复制请求标头?另外请注意您的网址'pollsController'是很奇怪的,尽量只** **投票我怀疑你将被重定向 – lp1051

回答

1

你跟你的AJAX调用发送正确的头,我会很感激,如果有人能说出?

{ 'X-Requested-With': 'XMLHttpRequest'} 

如果使用的是jQuery,你可以使用:

$.ajaxSetup({ 
    headers: { 'X-Requested-With': 'XMLHttpRequest' } 
}) 

您可以Chrome developer tools检查它的网络选项卡,在这里你必须选择根据您的要求。

,这里是the documentation for ajaxSetup()

编辑:

你可以把它放在这里:

<script> 
$('#btn').click(function(event) { 
    form = $("#PollIndexForm").serialize(); 
    $.ajaxSetup({ 
     headers: { 'X-Requested-With': 'XMLHttpRequest' } 
    }) 
    $.ajax({ 
     type: "POST", 
     url: 'pollsController/index';, 
     data: form, 
     success: function(data){ 
     } 
    }); 
    event.preventDefault(); 
    // return false; //stop the actual form post !important! 
}); 
</script> 
+0

jQuery的发送,默认情况下,没有必要设置。 – ceejayoz

+0

作为一个新手,我从来没有听说过这个我该怎么把这个文件是什么之前?我使用CakePHP的框架 – Yormie

+0

@ceejayoz不正确,取决于版本,系统,服务器等。例如,我必须做这样... – Kamil

1

在代码中,你有

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:许多RequestHandlerComponent的方法 只是代理了CakeRequest方法。以下方法已 弃用,并将在未来的版本中删除:isSsl()isAjax() isPost()isPut()isFlash()isDelete()getReferer()getClientIp()

+0

我刚刚做到了。相同的结果 – Yormie

相关问题