我使用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.
});
}
答案 0 :(得分:1)
根据它的外观,您可以为视图分配$data['information'] = $query_result;
所以$information
对象,而是直接将$query_result
传递给视图,而不是$data
所以改变:
$this->load->view("view_Profile_view", $query_result);
要:
$this->load->view("view_Profile_view", $data);