在 CodeIgniter 使用 AJAX

controller部分

  1. <?php   
  2.   
  3. class Ajax_post extends Controller {   
  4.   
  5.   function Ajax_post()   
  6.   {   
  7.     parent::Controller();     
  8.     $this->load->helper(array('url'));   
  9.   }   
  10.      
  11.   function index()   
  12.   {   
  13.        
  14.     $this->load->view('ajax_post');   
  15.   }   
  16.      
  17.   function post_action()   
  18.   {   
  19.      
  20.     if(($_POST['username'] == "") || ($_POST['password'] == ""))   
  21.     {   
  22.       $message = "Please fill up blank fields";   
  23.       $bg_color = "#FFEBE8";   
  24.        
  25.     }elseif(($_POST['username'] != "myusername") || ($_POST['password'] != "mypassword")){   
  26.       $message = "Username and password do not match.";   
  27.       $bg_color = "#FFEBE8";   
  28.          
  29.     }else{   
  30.       $message = "Username and password matched.";   
  31.       $bg_color = "#FFA";   
  32.     }   
  33.        
  34.     $output = '{ "message": "'.$message.'", "bg_color": "'.$bg_color.'" }';   
  35.     echo $output;   
  36.   }   
  37. }   
  38.   
  39. ?>  

jQuery 端
  1. $("#login_submit").click(    
  2.      
  3.     function(){   
  4.        
  5.         var username=$("#username").val();   
  6.         var password=$("#password").val();   
  7.          
  8.         $.ajax({   
  9.         type: "POST",   
  10.         url: "/ajax_post/post_action",   
  11.         dataType: "json",   
  12.         data: "username="+username+"&password="+password,   
  13.         cache:false,   
  14.         success:    
  15.           function(data){   
  16.                
  17.           }   
  18.            
  19.         });   
  20.   
  21.       return false;   
  22.   
  23.     });  

大概可以看的出來 jquery 用 POST 把資料丟出去後,在codeIgniter端也是用 $_POST 來接受,在做相對應的處理就好了。

參考
How to create a simple AJAX post in CodeIgniter using Jquery
在 CodeIgniter 中使用 jQuery 來達到 Ajax 的功能
Codeigniter 上利用 jQuery 實現 AJAX

留言