2017-04-15 107 views
1

我很抱歉聽起來令人困惑,但我會盡量以最好的方式解釋。從PHP控制器運行AJAX

在控制器我有一個函數搜索

public function search(){ 
    /* 
    I run my logics and get few URL from 
    where I need to fetch further data 
    the urls are saved in the URL array 

    $urls[0] = "http://url1.com/search1"; 
    $urls[1] = "http://url2.com/search2"; 

    I then set this in data variable and send it to view 
    so that It can be run in AJAX 

    I tired running get_file_contents but it executes 
    in series one after the other URL. 
    If there are 10 URL (5 secs per URL) the over all processing time 
    increases drastically 

    */ 

    $data["urls"] = $urls; 

    $resp = $this->load->view('ajaxer',$data,TRUE); 

    /* based on the $resp i need to run further business logic's */ 

} 

現在$ RESP實際上是給我唯一的HTML代碼。它不執行HTML,因此ajax沒有運行。

有關如何執行此操作的任何想法都將非常有用。

問候, 阿米特

+0

問題可能是因爲你沒有在ajax選項中包含'success'項目。選項'success'是一個接收控制器輸出的功能。在那個函數中你可以操縱html來使用返回的數據。添加javascript代碼,在其中創建ajax調用和要更新的視圖的html。 – DFriend

+0

@DFriend我確實有一個成功的選擇。如果它的成功,我更新一個特定的div html。然而,div是空的,我在$ resp –

+0

中得到完整的HTML代碼'$ resp'包含html,因爲這是'load-> view('someview')的預期目的;' - 返回內容HTML)在文件「someview」。對你想要達到的目標的明確解釋會非常有幫助。例如,您打算如何處理搜索網址? – DFriend

回答

1

你的代碼是absolutelly確定。但是你的javascript沒有得到任何響應數據(只有標題),因爲你沒有返回任何輸出。

如果你想「執行你的HTML」你需要與視圖行改成這樣:

$this->load->view('ajaxer',$data); 

或本:

$resp = $this->load->view('ajaxer',$data,TRUE); 
echo $resp; 
0

你忘了在控制器呼應輸出。除此之外,你需要對函數進行少量修改。

public function search(){ 
    /* 
    I run my logics and get few URL from 
    where I need to fetch further data 
    the urls are saved in the URL array 

     $urls[0] = "http://url1.com/search1"; 
     $urls[1] = "http://url2.com/search2"; 

    I then set this in data variable and send it to view 
    so that It can be run in AJAX 

    I tired running get_file_contents but it executes 
    in series one after the other URL. 
    If there are 10 URL (5 secs per URL) the over all processing time 
    increases drastically 

    */ 

    // You need to check either request came from Ajax request or not. If not it will echo passed string. It prevents to access this function besides Ajax request 
    if (!$this->input->is_ajax_request()) { 
     echo "Ajax Requests allowed."; 
     die; 
    } 

    $data["urls"] = $urls; 

    $resp = $this->load->view('ajaxer',$data,TRUE); 

    // Standard way to set response for output in json format. 
    // @param status will help to check all things goes correct or not. if not please pass false on the basis or your feature's requirement 
    $this->output->set_output(json_encode(array('status'=>true,'response'=>$resp))); 

    // Standard way to get output set above step. 
    $string = $this->output->get_output(); 
    echo $string; 
    exit(); 
    /* based on the $resp i need to run further business logic's */ 

} 

更新後的代碼在這裏。希望你找到答案