2014-10-31 179 views
-1

我想在ajax後獲得響應,但總是返回NULL。

我在想,已經嘗試了所有我可以......但希望有人能夠解決它。首先十分感謝。如果需要更多信息,請告訴我。

注:PHP function not returning any data to JQuery ajax method - 這個環節並沒有幫助我

這裏是jQuery代碼:

var post_id=3; 
     $.ajax({ 

      type: "POST", 
      url: "profile/ajax_get_new_posts", 
      data: { post_id : post_id }, 
      dataType: 'json', 
      success: function(data){ 

       console.log(data); 
       var current_content = $("ol#posts_container").html(); 

       $("ol#posts_container").html(data.content + current_content); 
      } 


     }); 

資料/ ajax_get_new_posts(它名爲.php)

function ajax_get_new_posts(){ 

     header('Content-Type: application/json'); 
      $post_id=$this->input->post('post_id'); 
      $chat_messages_html='testing'; 
      $result = array('status' => 'ok', 'content' => $chat_messages_html); 
      $result=json_encode($result); 
      return ($result); 
      exit(); 
     } 

如果我試着用var_dump($ result); die();給我正確的結果:

string(38) "{"status":"ok","content":"samoletite"}" 

在響應頭給我的Content-Length:0(它正在測試在本地主機上......不www.mywebsite)

Remote Address:[::1]:80 
    Request URL:http://www.mywebsite/bg/profile/ajax_get_new_posts 
    Request Method:POST 
    Status Code:200 OK 
    Request Headersview source 
    Accept:application/json, text/javascript, */*; q=0.01 
    Accept-Encoding:gzip,deflate 
    Accept-Language:en-US,en;q=0.8 
    Connection:keep-alive 
    Content-Length:9 
    Content-Type:application/x-www-form-urlencoded 
    Host:localhost 
Origin:http://localhost 
Referer:http://www.mywebsite/bg/profile 
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36 
X-Requested-With:XMLHttpRequest 
Form Dataview sourceview URL encoded 
post_id:3 
Response Headersview source 
Connection:Keep-Alive 
Content-Length:0 
Content-Type:application/json 
Date:Fri, 31 Oct 2014 13:24:56 GMT 
Keep-Alive:timeout=5, max=97 
....... 

CONSOLE.LOG給我:

null --->ajaxPostProfile.js:28 
Uncaught TypeError: Cannot read property 'content' of null --->ajaxPostProfile.js:31 

回答

3

而是使用return ($result);,使用echo。像這樣:

function ajax_get_new_posts(){ 

     header('Content-Type: application/json'); 
      $post_id=$this->input->post('post_id'); 
      $chat_messages_html='testing'; 
      $result = array('status' => 'ok', 'content' => $chat_messages_html); 
      $result=json_encode($result); 
      echo $result; 
      exit(); 
     } 

並再次測試。

+1

謝謝你非常非常....謝謝你救了我的時間從10個小時尋找解決方案。乾杯! – 2014-10-31 13:48:26

+0

不客氣!請將此答案設爲正確。謝謝。 – 2014-10-31 14:09:33

0

你可以在PHP中使用下面的語法返回JSON數據:

header('Content-Type: application/json'); 
    echo json_encode($result);