cakehp:使用电子邮件地址获取匹配的记录并在表单中显示


cakephp: fetching matching records using email addr and displaying in the form

当用户输入他的电子邮件地址时,我想使用电子邮件地址检查他/她的数据是否在数据库表中。如果它在那里,它应该获取匹配的记录(姓名、地址、城市、州、邮政编码)并在表单中显示。如果电子邮件地址不在db表中,则应该允许用户填写表单的其余部分。

我在这个项目中使用了cakeHP和MYSQL。这可以使用AJAX完成吗?做以上事情的最佳方法是什么?

谢谢。

最好的方法实际上是使用AJAX。我会将一个函数绑定到电子邮件字段的类型事件,然后让它在控制器中获取一个操作,该操作专门返回一个带有相应数据的JSON对象(如果有的话),然后使用Javascript将这些数据填充到相应的字段中。

我已经使用JQuery完成了以下操作。

在您看来:

注意:controller/action是它应该在控制器中调用的操作,#emailbox也被假设为电子邮件表单的id。#otherbox是其他表单元素的id的占位符。

<script type="text/javascript">                                         
   $(document).ready(function () {    
    $('input#emailbox').keyup(function () {
        // could do other stuff here, like show load bar or clear old results
        //run the ajax
        getPage();
    }); 
});

function getPage() {
    //generate the parameter for the php script
    var data = {email: $("#emailbox").val()};
    $.ajax({
        url: '/controller/action',  
        type: 'GET',        
        data: data,
        dataType: 'json',     
        cache: false,
        success: function (data) {  
            //add the content retrieved from ajax into whatever forms you like
            $("#otherbox").val(data.[User][information][here]);
            $("#otherbox").val(data.[User][information][here]);
            $("#otherbox").val(data.[User][information][here]);
            $("#otherbox").val(data.[User][information][here]);
        }       
    });
}                                 
 </script>

请注意,chrome-dev工具可以帮助调试返回的JSON对象,这样您就可以了解如何访问每个字段的相关数据。

在您的控制器中:

public function searchForDetails() {
        if($this->request->is('ajax')) {
            $this->autoRender = false;
//Get the email parameter data- this is one way to do it, you could also do it plenty of other ways
$email = $this->request->query['email'];
//Get user data- I have given an example of how to do so:
$userdata = $this->User->find('first', array(
    'conditions' => array(
        'User.email' => $email,
        'recursive' => -1));
return(json_encode($userdata));
            }
    }

这是一种方法。你必须做的工作是在chrome中调试JSON对象(使用命令shift j访问dev工具),并计算出对象内数组的布局,这样你就可以设置各个表单的值。我还没有测试过这种方法的效率,如果你正在开发Facebook,你可能不应该这样做。