我使用ajax爲我的網站動態加載一些內容,加載諸如註冊和登錄表單之類的東西時運行良好,因爲我不必向視圖本身發送任何數據(register_view
等)。
但是,當我嘗試加載不同的東西時,例如用戶的個人資料,它需要我將一些變量傳遞給視圖,以及當我遇到AJAX問題時。
我確定我發送的變量在控制器中被isset
和!empty
測試, 但是在視圖中,它突然變成了未定義的變量,這隻有在通過AJAX訪問配置文件時纔會發生。
PHP代碼:
控制器:當通過AJAX加載視圖時未定義的變量
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.
});
}
正因爲此,在 「未定義的變量」 的錯誤發生在哪裏? – Bergi
@Bergi哦!我忘了觀點,現在更新。 – Abdulaziz
嘗試做'$信息'vardump – xbonez