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');