2010-01-18 106 views
0

我有一個更新數據庫表的腳本。我需要返回一個JSON數組並使用JQUERY更新一些表。php和JSON幫助!

我的PHP腳本:

$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId); 
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults()); 
echo json_encode($output); 

jQuery代碼:

$("button").live("click", function(event){ 
        event.preventDefault(); 
        $.getJSON("startsearch.php",{ searchId: $(this).val() }, function(data){ 
         alert(data[0].status); 
        }); 

...現在的問題是,如果我使用$.post("startsearch.php",{ searchId: $(this).val() }, function(data))的腳本執行後,我也得到一個很好的警示與undefined值。如果我添加參數「json」腳本不會執行了。我試圖使用getJSON,但又是同樣的問題。

有人有什麼想法嗎?我絕望......這已經困擾我近一個星期,我仍然沒有設法解決它。

+1

您是否嘗試過使用Firebug記錄「數據」,以便檢查對象? – JAL 2010-01-18 21:35:24

+0

它應該是'data.status',而不是'data [0] .status'。看到我下面的完整答案。 – 2010-01-19 01:58:19

回答

0

在你的PHP文件一定要設置正確的內容類型:

header("Content-type: application/json; charset=utf-8"); 

所以jQuery可正確eval響應成JSON對象。

+0

'eval'是邪惡的:)使用來自http://json.org的'json2.js'以獲得更多的和平;) – 2010-01-19 01:59:11

0

你可以得到您的回覆數據如下:

alert(data.status); 
alert(data.results); 
alert(data.totalResults); 
0

請不要使用警報,螢火安裝到你的Firefox或啓用Chrome或Safari JavaScript控制檯。之後,你可以使用console.log(data);

我的猜測是,數據不是一個數組。也看看在jQuery文檔上的每個()exmaple http://docs.jquery.com/Ajax/jQuery.getJSON

0

那麼,我相信json2.js解析從AJAX請求返回的json數據。您可以從http://json.org下載。這個庫提供了一種更好的方式來解析任何字符串,並且如果sting不在json中,將會拋出一個異常。

我總是寫我的AJAX請求是這樣的:

$.post(URL, 
    { PARAM }, 
    function(data){ 
    try { 
     var r = JSON.parse(data); 
     //this for your code above 
     alert (r.status); //should be 'COMPLETED' 
    } 
    catch (e) { 
     //data is not in json format, or there are another exception in try block 
     //do something about it 
     alert('Exception occured, please check the data!'); 
    } 
}); 

當處理JSON,在PHP陣列將成爲JSON可變構件。所以如果你的php是$output['status'],那麼在json中,它將是r.status