我有一个表单,其中包含用于电子邮件的输入文本框和用于名称的输入文本框。
当用户输入他/她的电子邮件ID时,应自动使用Ajax在名称输入文本框中提取并显示该电子邮件ID的正确名称(在数据库中)。
以下是我的代码,但是当我输入电子邮件ID并按下标签按钮时,没有显示任何名称(AJAX的工作方式)。有人能指出我出错的地方吗?谢谢。
我正在尝试使用Cakephp,jquery和ajax。
来自浏览器的源代码:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#MerryParentEmail").bind("keyup", function (event)
{$.ajax({async:true, dataType:"html", success:function (data, textStatus)
{$("#MerryParentName").html(data);}, type:"post", url:"\/merry_parents\/getname"});
return false;});});
//]]>
</script>
view.ctp
<?php
echo $this->Session->flash();
echo $this->Form->create('MerryParent', array('default'=>false));
echo '<fieldset>';
echo '<legend>Parent Information</legend>';
echo $this->Form->input('MerryParent.email');
if (isset($name))
echo $this->Form->input('MerryParent.name', array('label'=>'Parent/Guardian Name','value'=>$name));
else
echo $this->Form->input('MerryParent.name', array('label'=>'Parent/Guardian Name'));
$this->Js->get('#MerryParentEmail');
$this->Js->event('keyup',
$this->Js->request(array(
'controller'=>'merry_parents',
'action'=>'getname'),
array('async'=>true,
'update'=>'#MerryParentName',
'method'=>'post')
)
);
echo '</fieldset>';
echo $this->Form->end('Submit');
?>
merry_parents_controller.php
<?php
class MerryParentsController extends AppController{
public $many_children_flag='false';
var $name='MerryParents';
function beforeFilter()//executed before any controller action logic
{ parent::beforeFilter();
$this->Security->validatePost=false; //set to false to completely skip the validation of POST request
//parent::beforeFilter();
if(isset($this->Security) && $this->RequestHandler->isAjax() && $this->action = 'getname'){
$this->Security->enabled = false;
$this->autoRender=false;
}
}
function getname(){
if (!empty($this->data)){
//var_dump($this->data);
$merryparent_info=$this->MerryParent->getMerryParents($this->data['MerryParent']['email']);
//print_r($merryparent_info);
$name=$merryparent_info['MerryParent']['name'];
$this->set('name',$name);
//$this->render('/merry_parents/ajax_input');
}
}
function view(){
//$name='';
//var_dump($this->data);
//$this->getname();
}
merry_parent.php模型
function getMerryParents($field_value){
if (is_int($field_value))
$conditions=array('merryParent.id'=>$field_value);
else
$conditions=array('merryParent.email'=>$field_value);
//debug($conditions);
$merryparent_info=$this->find('first',array(
'conditions'=>$conditions,
'recursive'=>-1 //fetches merry_parents table data only not the associated data
));
//debug($merryparent_info);
return $merryparent_info;
}
答案 0 :(得分:0)
您必须将表单数据发送回控制器。 将JS请求绑定到keyup事件时,您将通过CakePHP代理方法分别输入jQuery jQuery。并且没有自动绑定到您的表单数据,因此您必须自己管理它。
然而CakePHP中有一个方便的参数!尝试
$this->Js->get('#MerryParentEmail');
$this->Js->event('keyup',
$this->Js->request(array(
'controller'=>'merry_parents',
'action'=>'getname'),
array('async'=>true,
'update'=>'#MerryParentName',
'dataExpression'=>true,
'data'=>$this->Js->serializeForm(array('inline'=>true)),
'method'=>'post')
)
);