2011-05-23 70 views
0

我正在使用jQuery的ajax方法將一些數據發佈到服務器並取回響應。雖然服務器端php代碼正在返回一個json編碼的字符串/數組,但響應會返回爲空。PHP函數不返回任何數據給JQuery ajax方法

有人能指出我犯的錯誤嗎?下面是如何使用我正在觸碰postData.php頁面的jquery ajax方法。

 $.ajax({ 
      url:'postData.php', 
      type:'POST', 
      data:data, 
      dataType: "json", 
      success: function(response){ 
       console.log(response); 
      } 
     }); 

postData.php中的內容非常直接,因爲我仍在開發它。

$data = array(); 
//inside postData.php 
    $data['test']=1; 
    return json_encode($data); 

它應該返回一個json字符串,但它返回null。我也嘗試在$ data數組聲明後面回顯一個字符串,它在firebug中回顯它,但是響應是當我在成功回調中執行console.log時,它會返回爲空。

回答

2

這是所有在postData.php?你需要把它寫出到緩衝區(echo json_encode($ data);)。

+0

謝謝!!我已經使用jquery和ajax了很多,並且急於快速完成任務,我犯了這個有趣的錯誤! – macha 2011-05-23 01:00:29

3

爲了得到結果回到你的Ajax功能,必須呼應它,而不是返回,如:

$data = array(); 
$data['test']=1; 
echo json_encode($data); 
+0

謝謝!我已經使用jquery和ajax了很多,並且急於快速完成任務,我犯了這個有趣的錯誤! – macha 2011-05-23 01:00:05

0

像morgar指出了這一點,你應該呼應的數據備份,而不是使用的回報。

$data = array(); 
$data['test']=1; 
echo json_encode($data); //echo instead of return 

同時,在你的ajax成功函數中,你應該像數組一樣訪問響應。

**Incorrect** 
console.log(response); //--> would return an error 

**Should Be** 
console.log(response[0]); //--> read the returned first array element 
+0

爲什麼會是一個錯誤?他只是console.log()'數組。 – 2011-05-23 02:15:56

+0

@John Green - PageSpike:嗯,我會認爲這會導致錯誤,因爲如果他有2個元素在數組中,要獲得它的值將是響應[0]和響應[1]?我錯了嗎? – maomaopop 2011-05-26 02:43:17

+0

通常稱爲稀疏數組。這樣做是合法的。 – 2011-05-26 05:23:54