2013-09-30 26 views
0

我使用下面的代碼段從形式到一個PHP腳本,將使用一個類做一些計算髮送數據:jQuery將不接受json_encode()數據

$.ajax({ 
    type: "POST", 
    url: "test2.php", 
    data: values, 
    success: function(returnedData) { 
     $("#result").html(returnedData); 
    }, 
    error: function(){ 
     alert("failure"); 
     $("#result").html('error while submitting'); 
    } 
}); 

我的PHP腳本創建一個數組,我用JSON編碼,然後回顯

$jsonString = array(
    'monthText' => $Month->getMonthText($month), 
    'gross' => $formatGross, 
    'net' => $formatNet 
    ); 
echo json_encode($jsonString); 

到目前爲止這麼好。但我並不十分熱衷於顯示原始的JSON。我想在將文本寫入文檔之前對其進行格式化。我試過$.parseJSON()$.getJSON()但他們都沒有工作。 jQuery文檔說它需要一個字符串,但不是json_encode()使我的數組字符串?是不是echo使它成爲一個字符串?爲什麼我在我的jQuery文件中收到錯誤Uncaught SyntaxError: Unexpected token {?我的理論是它沒有單引號。

我試過在我的PHP腳本中使用header('Content-type: application/json'),我也試過dataType: json在我的AJAX POST中,但沒有任何工作。

我在做什麼錯?

+0

你試過看着實際上正在返回什麼,並使用您的瀏覽器的調試工具發送到您的Web服務器? – JAL

+0

@davidkonrad [它看起來不像'true'是有效的第二個參數](http://php.net/manual/en/function.json-encode.php)。 – Blazemonger

+0

此外,請繼續前進,並在您的Ajax函數中設置數據類型,並在PHP中設置內容類型標頭... – JAL

回答

4

從評論它聽起來像你使用json_encode錯誤。將每段數據存儲到一個數組中,然後對數組進行編碼。

$data = array(); 
for($i=0;$i<$something;$++) { 
    $data[] = array(
     'monthText' => $Month->getMonthText($month), 
     'gross' => $formatGross, 
     'net' => $formatNet 
    ); 
} 

echo json_encode($data); 

然後你的Javascript將需要

$.ajax({ 
    type: "POST", 
    url: "test2.php", 
    dataType:"json", 
    data: values, 
    success: function(returnedData) { 
     //returnedData will now be an array Object 
     for(var i=0; i<returnedData.length; i++) { 
      $("#result").html(returnedData[i].monthText); 
     } 
    }, 
    error: function(){ 
     alert("failure"); 
     $("#result").html('error while submitting'); 
    } 
}); 
0

解析,使用jQuery.parseJSON(returnedData);

+0

也嘗試alerting或console.log您的「returnedData」以查看您是否獲取數據。 – Rajesh

+0

當使用'dataType:「json」'時,jQuery可以自動解析json'不需要使用'.parseJSON' –

+0

爲真,但@Marcus在他剛剛提到的問題中沒有使用它。 – Rajesh

0

像這樣在你的ajax調用中添加dataType。

$.ajax({ 
    type: "POST", 
    dataType:"json", 
    url: "test2.php", 
    data: values, 
    success: function(returnedData) { 
     $("#result").html(returnedData); 
    }, 
    error: function(){ 
     alert("failure"); 
     $("#result").html('error while submitting'); 
    } 
});