使用CakePHP中的Ajax搜索数据

时间:2014-06-04 11:03:02

标签: ajax cakephp search

我正在使用CakePHP 2.3.6。在我的一个项目中,我必须使用AJAX实现Searching胎儿。通常,这是有效的,但我希望页面不会重新加载,结果表将立即更新数据。

这是Controller代码:

public function searchData(){
    $this->set(............);
    $this->set(............);
    $this->set(............);
    if($this->request->is('post')){
$this->layout='ajax';
$this->autoRender=false;
       if(!empty($data)){
          $data=$this->request->data;
          // Generating options
          .
          .
          .
          $result=$this->ModelName->find('all',$options);// "$options" is generated options
          if(!empty($result)){
$this->set(compact($result));
$this->set('_serialize',array('result'));
print_r(json_encode($result));
             $this->Session->setFlash("Searching Applicants Successful");
             $this->set('result',$result);
          }else
             $this->Session->setFlash("No data found");
       }else
          $this->Session->setFlash("You didn't give any info to search for");
    }
}

我的View文件(search_data.ctp):

<h3>Search Result</h3>
<?php
    echo $this->form->create();
    echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
    echo $this->Form->submit('Search');
    echo $this->Form->end();
<div id="searchResult">
<?php if(!empty($result)){?>
       <table class="table table-striped table-bordered table-hover">
           <thead>
              <th>Field 1</th>
              <th>Field 2</th>
              <th>Field 3</th>
              <th>Field 4</th>
           </thead>
           <tbody>
<?php foreach($result as $applicant){?>
               <tr>
                  <td><?php echo $result['ModelName']['field1'];?></td>
                  <td><?php echo $result['ModelName']['field2'];?></td>
                  <td><?php echo $result['ModelName']['field3'];?></td>
                  <td><?php echo $result['ModelName']['field4'];?></td>
               </tr>
<?php }?>
           </tbody>
       </table>
<?php
     }else
        echo "No data found";
?>
</div>

在这里,我想要的是,当我提交表格时,&#34;结果&#34; div将立即显示结果数据,并在表格中进行组织。我想在这里使用Ajax,以便用户立即获得结果,它可以改善性能和用户体验。

我看过一些YouTube视频,他们在其中加载了包含结果的另一个页面,并在div中显示该页面(称为&#34;成功&#34; div大部分时间:)),使用Ajax。我能做到。但是,我只想在1页中做所有事情,我不想用2页来做。

我尝试了这个用于ajax请求并更新我的&#34;结果&#34; div(在我的search_data.ctp文件中):

$this->Js->get('.search-form')->event('submit',$this->Js->request(array('controller'=>'cntrlr_name','action'=>'searchData'),array('async'=>true,'update'=>'#searchResult')));

当我运行页面时,这是输出:

[{"Applicant":{"id":"3","name":"Name 2","email":"ssaha.316@gmail.com","mobile":"9082730572","contact_phone":"3465360980","office_phone":"2437845693","correspondence_address":"Correspondence Address 2","permanent_address":"Permanent Address 2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"},"ApplicantAcademicQualification":[{"id":"2","applicant_id":"3","level":"Bachelor(Pass)","degree_title":"B.A.","passing_year":"1999","institution":"Institution 2","result":"4.2","major":"Bengali Literature","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantEmploymentHistory":[{"id":"2","applicant_id":"3","employer":"Employer 2","position_held":"Position 2","industry":"Industry 2","department":"Department 2","major_responsibilities":"Responsibility 2","job_location":"Local","key_achievement":"Achievement 2","served_from":"1999-08-15","served_till":"2010-02-12","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantOther":[{"id":"2","applicant_id":"3","academic_activities":"Academic Activities 2","non_academic_activities":"Non Academic Activities 2","main_reason_for_applying":"Reason 2","worked_before":"0","last_position":"","work_location_constraint":"1","ready_to_join_on":"2008-08-14","expected_salary":"30k+","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantProfessionalQualification":[{"id":"2","applicant_id":"3","name_of_certificate":"Certificate 2","institute":"Institute 2","from":"2002-10-17","to":"2007-10-12","location":"Local Ins.","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantTraining":[{"id":"2","applicant_id":"3","title":"Title 2","institute":"Institute 2","training_year":"1995","location":"In Company","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}]},{"Applicant":{"id":"2","name":"Name 1","email":"user1@email.com","mobile":"715414918934","contact_phone":"2357295090","office_phone":"083656987398","correspondence_address":"Address 1_1","permanent_address":"Address 1_2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"},"ApplicantAcademicQualification":[{"id":"1","applicant_id":"2","level":"Secondary","degree_title":"S.S.C","passing_year":"2009","institution":"Institute 1","result":"4","major":"Science","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantEmploymentHistory":[{"id":"1","applicant_id":"2","employer":"Employer 1","position_held":"Position 1","industry":"Industry 1","department":"Department 1","major_responsibilities":"Responsibilities 1","job_location":"Local","key_achievement":"Achievements 1","served_from":"2005-03-12","served_till":"2007-11-26","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantOther":[{"id":"1","applicant_id":"2","academic_activities":"Academic Activities 1","non_academic_activities":"Non Academic Activities 1","main_reason_for_applying":"Reason 1","worked_before":"1","last_position":"Last Position 1","work_location_constraint":"1","ready_to_join_on":"2008-07-10","expected_salary":"20k-25k","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantProfessionalQualification":[{"id":"1","applicant_id":"2","name_of_certificate":"Certificate 1","institute":"Institute 1","from":"2011-10-11","to":"2012-09-11","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantTraining":[{"id":"1","applicant_id":"2","title":"Title 1","institute":"Institute 1","training_year":"2013","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}]}]

有可能吗?我该怎么做 ?请帮帮我。

感谢。

2 个答案:

答案 0 :(得分:1)

更新你的函数searchData:

  public function searchData(){
      //just empty for showing the form only
  } 

添加ajax函数:

  public function ajax_search(){
   $this->layout="ajax";
   $result = array();
   $field1 = $_POST["field1"];
   $field2 = $_POST["field2"];
   $field3 = $_POST["field3"];
   $field4 = $_POST["field4"];
   if( $field1 &&  $field2 &&  $field3  &&  $field4 ){ //change this depending on your queries
         $data=$this->request->data;
         // Generating options
         .
         .
         .
         $result=$this->ModelName->find('all',$options);// "$options" is generated option
    }
    $this->set("result", $result);
   }

添加视图ajax_search.ctp:

  <?php if($result):?>
  <table class="table table-striped table-bordered table-hover">
          <thead>
             <th>Field 1</th>
             <th>Field 2</th>
             <th>Field 3</th>
             <th>Field 4</th>
          </thead>
          <tbody>
         <?php foreach($result as $applicant){?>
              <tr>
                 <td><?php echo $result['ModelName']['field1'];?></td>
                 <td><?php echo $result['ModelName']['field2'];?></td>
                 <td><?php echo $result['ModelName']['field3'];?></td>
                 <td><?php echo $result['ModelName']['field4'];?></td>
              </tr>
          <?php }?>
          </tbody>
      </table>
   <?php else:?>
      No results.
  <?php endif;?>

更新searchData.ctp:

 <h3>Search Result</h3>
 <?php
    echo $this->Form->create("Search",array("default"=>false, "id"=>"SearchForm"));
    echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
     echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
    echo $this->Form->submit('Search');
   echo $this->Form->end();
   <div class="result">
;?>

<script type="text/javascript">
 $(document).on('submit','#SearchForm',function(){
     $.ajax({
   type: "POST",
   data:{
      field1:$("#SearchField1").val, // the ids of your input or you can modify these if you have assigned ids to the input
         field2:$("#SearchField2").val,
         field3:$("#SearchField3").val,
         field4:$("#SearchField4").val
  },
      beforeSend: function(){
        $("#result").html("loading...");
      }
  url: "<?php echo $this->base;?>/{insert your controller name here}/ajax_search/",
  success:function(data) {
         $("#result").html(data);
      }
   });              
}); 
</script>

答案 1 :(得分:0)

以下是步骤:

以下是example如何使用jQuery模板,以及here它的文档

Here是另一种方法

<强>更新

简单的返回json结果来自您的搜索方法:

public function searchData(){
$this -> layout = 'ajax';
$this -> autoRender = false;
if($this->request->is('post')){
   if(!empty($data)){
      $data=$this->request->data;
      // Generating options
      ...
      $result = $this->ModelName->find('all',$options);// "$options" is generated options
      $this -> set(compact($result));
      $this -> set('_serialize',array('result'));
      echo json_encode($result);
    }
  }
}

使用并循环JSON结果数据