我的 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')) {
}
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/