jQuery(function(){
jQuery('.ajax-function').click(function(){
jQuery.ajax({
url : '<?= $root_path.'/helloworld/ajaxFunction'; ?>',
data: {
'username':'ceshi',
'password':'12345'
},
type: 'get',
dataType:'JSON',
success:function(data){
},
error:function(a,b,c){
console.info(c);
}
});
});
});
2、控制器:</script>
注:(1)通過url傳遞參數:前端傳遞N個參數,那麼對應在controller裏面的函數就應該設置N參數,如:public function ajaxFunction($username=null,$password=null){$username = $this->input->get('username');$password = md5($this->input->get('password'));return false;}
url : '<?= $root_path.'/helloworld/ajaxFunction/ceshi_canshu_1/ceshi_canshu_2'; ?>',
type: 'get',
dataType:'JSON',
success:function(data){
},
error:function(a,b,c){
console.info(c);
}
});
//前臺傳遞2個參數‘ceshi_canshu_1/ceshi_canshu_2’,那麼在controller對應的函數中就應該有‘$var_1和$var_2’來對應
public function ajaxFunction($var_1=null,$var_2=null){
}
(2)通過data傳遞參數:controller函數中對應的函數不需要設置參數,如:
jQuery.ajax({
url : '<?= $root_path.'/helloworld/ajaxFunction'; ?>',
data: {
'username':'ceshi',
'password':'12345'
},
type: 'get',
dataType:'JSON',
success:function(data){
},
error:function(a,b,c){
console.info(c);
}
});
//controller對應的函數中不需要設置參數
public function ajaxFunction(){
}
注:在不使用url傳遞參數時,後臺獲取傳遞的參數方式需要根據前端設置的Ajax請求類型而改變,如:
1)前端的的ajax設置的“type: 'post'”,那麼後臺獲取參數時:$var_1 = $this->input->post('var_1');
2)前端的的ajax設置的“type: 'get'”, 那麼後臺獲取參數時:$var_2 = $this->input->get('var_2');