[英]Sending data using AJAX and redirect in PHP
使用AJAX單擊按鈕時,我正在發送數據。 當數據發送到PHP服務器(Codeigniter框架)時,它將在服務器上進行一些處理並從數據庫中檢索數據,然后應將檢索到的數據重定向到另一個頁面,
下面是AJAX調用,
jQuery.ajax({
url: baseURL + "admin/reports/",
data: {rep_id:report_ids},
type: "POST",
success:function(data){
var objData = jQuery.parseJSON(data);
}
});
以下是PHP處理,
$data = $this->admin_model->fetch_date($this->input->post('rep_id', TRUE));
$this->load->view('user/report', $data);
如果我使用上面的PHP代碼,那么它將不會重定向到另一個頁面,但是它將嘗試將完整的視圖文件作為AJAX發送一個響應(我可以通過inspect在瀏覽器中看到),
所以我的問題是,如何使用完整的$data
數組執行重定向?
首先,您必須使用參數中的id重定向到所需的視圖,例如
$para array( 'id'=>$report_ids);
redirect('admin/reports/'.$para);
重定向到URL之后,您應該已經發送了ajax調用
jQuery.ajax({
url: baseURL + "admin/reports/",
data: {rep_id:report_ids}, // Here you have to get your id from url with jQuery
type: "POST",
success:function(data){
var objData = jQuery.parseJSON(data);
}
});
現在,您在重定向頁面上擁有了完整的數據。
您可以使用jQuery將其附加到任何div。
嘗試這樣...在php中,必須使用json_encode()
來發送回響應,如下所示。
$data = $this->admin_model->fetch_date($this->input->post('rep_id', TRUE));//Fetch your data in array format
echo json_encode($data);
然后在您的AJAX中。
jQuery.ajax({
url: baseURL + "admin/reports/",
data: {rep_id:report_ids}, // Here you have to get your id from url with jQuery
type: "POST",
success:function(data){
var objData = jQuery.parseJSON(data);//objData is in object format...
//try console.log(objData);
window.location.href('user/report?name='+objData.name);//name is attribute of your object
}
});
您以錯誤的方式使用ajax!
當通過ajax調用php過程時,在php中重定向不再有意義。 通過ajax檢索數據后,應該在jQuery中進行重定向。
首先,僅在php中回顯json數據:
$data = $this->admin_model->fetch_date($this->input->post('rep_id', TRUE));//Fetch your data in array format
echo json_encode($data);
然后在檢索數據時重定向:
jQuery.ajax({
url: baseURL + "admin/reports/",
data: {rep_id:report_ids}, // Here you have to get your id from url with jQuery
type: "POST",
success:function(data){
// do not pars json!
window.location = '/user/report?data=' + objData; // sending json as a string in query string
}
});
現在在/user/report
視圖中,使用jQuery解析json以供使用
更新:
我認為您根本不需要ajax! Ajax旨在幫助我們避免重定向!
嘗試這個 :
<a href="/admin/report"> GET REPORT! </a>
並在您的php中:
$data = $this->admin_model->fetch_date($this->input->post('rep_id', TRUE));
$this->load->view('user/report', $data);
如果使用代碼點火器,則可以嘗試使用flashdata
(臨時會話)和header
嘗試:
$data = $this->admin_model->fetch_date($this->input->post('rep_id', TRUE));
$this->session->set_flashdata('tempValue', '$data');
header("Location: http://yousite/user/report");
exit;
然后在您的user/report
中獲取數據使用:
$this->session->flashdata('tempValue');
但我認為你不需要阿賈克斯可言,擺在首位,如果使用標准html
和POST
數據到您的admin/reports/
使用簡單的web form
與action="admin/reports/"
。 在這種情況下,您的PHP
可以與OP中的完全相同
我刪除了AJAX,並在JS中進行了簡單的重定向,
window.location = baseURL + 'admin/reports/test/' + rep_id;
然后是PHP代碼,使用rep_id
作為函數變量並進行處理並加載了View頁面,
public function test($in)
{
$data['test'] = $this->admin_model->fetch_insight($in);
$this->load->view('user/report', $data);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.