2011-01-28 63 views
0

我想创建一个twitter应用程序,其中用户输入一些数据到表单中,并通过使用ajax(jQuery库)用户看到他们提交的实时转到顶部的所有其他数据。PHP(Codeigniter)和ajax帮助

它的工作方式是用户提交表单并将数据提交给数据库,我也想使用ajax将数据添加到数据列表中。

我的问题是我只能访问PHP方法从ajax请求创建的数据,如果我在我的php方法中使用了echo $var;,这对我来说看起来不正确,有些人可以告诉我我做错了什么吗?

public function feed() { 
     $this->load->library('form_validation'); 
     $this->load->helper('dates'); 
     $data['feed'] = $this->f->get_feed_by_employer($this->session->userdata('employer_id')); 
     $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); 
     $this->form_validation->set_rules('content', 'content', 'required|trim|max_length[140]'); 
     $this->form_validation->set_rules('retrain', 'retrain position', 'trim|max_length[1]'); 

     if ($this->form_validation->run() == FALSE) 
     { 
      echo validation_errors('<div class="error">', '</div>'); 
      $this->template->build('employer/feed', $data); 
     } 
     else 
     { 
      $insert = array(
       'content' => $this->input->post('content'), 
       'retrain' => $this->input->post('retrain'), 
       'created_at' => time(), 
       'employers_id' => $this->session->userdata('employer_id') 
      ); 

      if($this->f->insert($insert)) { 
       echo $insert['content']; 
      } 
     } 
} 

和jQuery的

$('#employer_feed').submit(function(){ 
    $.ajax({ 
     url: '/employer/feed', 
     data: $('#employer_feed').serialize(), 
     type: 'POST', 
     success:function(html) { 
      $('#feed').append('<div class="feed_item">'+html+'</div>'); 
     } 
    }); 
    return false; 
}); 

回答

2

有没有用Ajax请求打交道时使用echo的问题,其实这是要走的路。您也可以使用echo json_encode($output);,具体取决于您的ajax请求类型。

检查此article,使用is_ajax知道何时到echo以及何时加载您的意见是一种干净的方式!在config/autoload.php

<?php 

function is_ajax(){ 
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
      && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); 
} 

而且:

所以application/helpers/文件夹中创建一个文件is-ajax_helper.php

$autoload['helper'] = array('is-ajax'); 

而就检查它是否是一个Ajax调用或不!

编辑:
因为笨2.0正式出来,现在的插件与助手代替,我已经更新我的答案。

0

如今,您只需使用$this->input->is_ajax_request()the input class)即可获得与@ifaour手工制作的帮手相同的效果。