使用AJAX和Codeigniter获取数据?

我试图将数据提取到表中,没有任何反应。

  1. 没有表格出现
  2. 没有提取数据

调节器

public function indexajax() { if($this->input->post("action")=='FetchAllUserUingAjax') { $this->load->model("usersmodel"); $data["allu"]=$this->usersmodel->ShowAllUsers("users"); $data['pagetitle']=" -->All Users Using Ajax<--"; foreach ($allu as $a): echo' '.$a->id.' '.$a->username.' '; endforeach; $this->load->view("template/admin/header",$data); $this->load->view("users/allusersusingajax",$data); $this->load->view("template/admin/footer"); } } 

jQuery的

   $(document).ready(function () { FetchAllUserUingAjax(); function FetchAllUserUingAjax() { $.ajax({ url:'Users/indexajax', method:"post", success:function (data) { $(".userdataajax table").append(data); } }) var action="FetchAllUserUingAjax"; $.ajax({ url:"Users/indexajax", method:"post", data:{action:action}, success:function (data) { $(".userdataajax table tr ").not("table tr:first").remove(); $(".userdataajax table").append(data); Table(); } }) } })  

模型

 public function ShowAllUsers() { $sql=$this->db->get("users"); return $sql->result(); } 

视图

 
# name image full name email usertype status reg date reg time delete edit Activate disactivate

您的代码提示未显示的其他相关代码。 我正在把你所展示的东西当作所有需要知道的东西。 这是我基于这个前提所看到的。

一,观点。 在表中添加id 。 它使JQuery选择器变得如此简单。 JavaScript位于此文件中,即“users / allusersusingajax.php”。

 
# name image full name email usertype status reg date reg time delete edit Activate disactivate

控制器需要两种方法。 一个显示另一个表来获取行。 这是Users.php文件

 //show the page which includes the basic  and header row public function indexajax() { // The code and question text give no reason for this conditional test // So I'm removing it //if($this->input->post("action") == 'FetchAllUserUingAjax') //{ $data['pagetitle'] = "-->All Users Using Ajax<--"; $this->load->view("template/admin/header", $data); $this->load->view("users/allusersusingajax"); $this->load->view("template/admin/footer"); //} } //respond to ajax request public function get_all_users() { $this->load->model("usersmodel"); $allu = $this->usersmodel->ShowAllUsers("users"); $out = ''; //if the model returned an empty array we still have a string to echo //using PHP's output buffer to simplify creating a big string of html ob_start(); //start output buffering foreach($allu as $a): ?> 

阅读PHP的输出控制function

我首先更新我的模型以返回一个数组:

 return $sql->result_array(); 

然后在您的控制器中,您不需要加载视图:

  public function indexajax() { if($this->input->post("action")=='FetchAllUserUingAjax') { //set content type header("Content-type: application/json"); $this->load->model("usersmodel"); echo json_encode( $this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one ); } } 

然后在你的ajax回调中:

 success: function(resp){ $.each(resp, function(k,v){ console.log(v); }); } 
id; ?>username; ?>