我使用 ajax 为我的网站动态加载一些内容,它在加载注册和登录表单等内容时效果很好,因为我不必向视图本身发送任何数据(register_view
等)。
但是,当我尝试加载不同的东西时,例如用户的配置文件,它需要我将一些变量传递给视图,并且当我遇到 AJAX 问题时。
而且我确定我发送的变量在控制器中经过测试isset
,!empty
但是在视图中,它突然变成了未定义的变量,这只发生在通过 AJAX 访问配置文件时。
PHP代码:
控制器:
if($this->uri->segment(4)){//if viewing a specific profile.
/*escape the uri segment*/
$segment = intval($this->uri->segment(4));
if($segment == 0){//the uri segment was a string
/*display error message.*/
$data['content'] = 'redirect_message';
$data['information'] = 'Could\'nt find the profile!, please try again.';
$this->load->view('templates/manage', $data);
}
else{//else , the uri segment is a number, considered safer.
$query_result = $this->db_model->getProfile($segment);//get the Profile
/*check if any results were returned.*/
if($query_result->num_rows() > 0){
/*load a view to display the specified Profile.*/
$data['information'] = $query_result;
if($this->input->is_ajax_request())//requesting via ajax, display the content only.
$this->load->view("view_Profile_view", $query_result);
else{
$data['content'] = 'view_Profile_view';
$this->load->view('templates/manage', $data);
}
}
else{ //no rows returned.
/*show error message.*/
$data['content'] = 'redirect_message';
$data['information'] = 'Error viewing the Profile!';
$this->load->view('templates/manage',$data);
}
}
}
视图(view_Profile_view
):
/*display the profile:*/
$row = $information->row();//error occurs here!
echo $row->username.'</br>';
echo $row->email;
jQuery/JS 代码:
var base_url = "/";
var site_url = "/index.php/";
$(document).ready(function(){
$('.ajax_anchor').click(function(){
loadForm(this);
return false;
});
});
function loadForm(anchor){
var splitted_url = $(anchor).attr('href').split("/");
if(splitted_url.length == 7){//probably accessing /site/login or /site/register not something like /site/profiles/view/[ID].
var url = splitted_url[splitted_url.length-2]+"/"+splitted_url[splitted_url.length-1];
}
else if(splitted_url.length == 9) {//probabbly accessing /site/profiles/view/[ID] not something like /site/login.
var url=
splitted_url[splitted_url.length-4]+"/"
+
splitted_url[splitted_url.length-3]+"/"
+
splitted_url[splitted_url.length-2]+"/"
+
splitted_url[splitted_url.length-1]+"/"
;
}
var csrf_token = $.cookie('csrf_cookie_name');//holding the csrf cookie generated by CodeIgniter, using jQuery cookie plugin
$.ajax({
type: "POST",
url: site_url+url,
data: {csrf_test_name:csrf_token}//pass the csrf token otherwise codeigniter will return an error(500).
}).done(function( html ) {
var ajaxResult$ = $('#ajax_result');//ajax_result is an empty div, used to display ajax results.
ajaxResult$.empty().append(html).dialog();//dialog:is a jquery-ui function.
});
}