2011-05-27 156 views
1

我仍然試圖弄清楚如何使用JSON ..有人可以幫我理解如何處理這個響應。我的查詢是:幫助處理JSON響應

$.ajax({ 
url: s7query, 
dataType: 'jsonp', 
success: function(){ 
// how do I deal with the response? 
} 
}); 

的JSON我查詢返回(選配1或0):

s7jsonResponse(
{"catalogRecord.exists":"1"},""); 

所有我從這個需要的是數量和它放入一個變量,這樣我可以然後針對該結果運行條件邏輯。感謝您的任何幫助瞭解此...

如果我嘗試並用任何函數處理成功螢火蟲只是返回s7jsonResponse未定義。我試圖將它定義爲請求之外的變量。現在我在firebug中看到它從所有請求中返回json,但它將它們作爲錯誤返回,現在說s7jsonResponse不是函數。我想我很接近..請幫忙!

回答

1

好吧,我錯過了json p部分!您只需要爲s7jsonResponse定義一個方法。

function s7jsonResponse (jsonData, someString) { 
    alert(jsonData["catalogRecord.exists"]); 
    // deal with the response here 
} 

See this for details on JSONP

初始響應

我注意到 catalogRecord.exists,這已成爲一個 .,它不會提取。如果您沒有足夠的理由這麼做,可以將其更改爲 catalogRecordExists並使用下面的解決方案。

$.ajax({ 
url: s7query, 
dataType: 'json', //removed jsonp in the last edit 
success: function(data){ // this is the method that executes on success 
      // parseJSON is not required as you already put it in dataType 
      // alert(($.parseJSON(data))["catalogRecord.exists"]); 
      alert(data["catalogRecord.exists"]); 
     } 
}); 

注意: 您指定JSONP爲您發回應該數據= {"catalogRecord.exists":"1"}

您可以使用$.getJSON做同樣的(它在內部調用$.ajax

+0

謝謝...但是這仍然拋出s7jsonResponse沒有定義 – Zac 2011-05-27 18:19:07

+0

響應將是可變的錯誤'data' – Lobo 2011-05-27 18:29:14

+0

所以這是錯誤:'s7jsonResponse不defined'。向我們展示函數's7jsonResponse'。 – Rudie 2011-05-27 18:51:50

1

數據類型在你的ajax調用中。這告訴Web服務返回一個jsonp響應,而不是純粹的json響應。所以,考慮到你得到的響應,你應該定義一個名爲s7jsonResponse的函數,它帶有兩個參數。第一個應該是一個json對象,並且您必須查看api才能獲得第二個,因爲在您給我們的示例中它是空的。

在您的s7jsonResponse方法中,您可以查看返回的數據,但正如Lobo指出的那樣,您的名稱中有點。因此,您將不得不使用括號表示法訪問該屬性。喜歡的東西:

function s7jsonResponse(obj, nothing) 
{ 
    var exists = obj["catalogRecord.exists"]; 
    // do your stuff with your 1 or 0 which is stored in exists 
} 
+0

謝謝你!我想念它作爲json-with-ap。 – Lobo 2011-05-27 19:36:39