2012-01-17 29 views
0

我想知道是否有可能獲得JQuery的方法的getJSON的外部訪問返回的JSON數據..這樣的事情之外..JQuery的/ JSON - 需要將數據訪問由JSON返回的代碼塊

var price = ""; 
$.getJSON("../JSONDeliveryPrice", null, function (data) { 
    price = eval(data.price); 
}); 
console.log(price); 

這是行不通的,有沒有另外一種方法可以獲得價格以外的價格?

+2

異步代碼 – jantimon 2012-01-17 08:36:13

+1

您需要使用同步請求。這是偉大的答案熱做到這一點:http://stackoverflow.com/questions/933713/is-there-a-version-of-getjson-that-doesnt-use-a-call-back – Samich 2012-01-17 08:36:33

+0

使呼叫同步向後。處理響應的代碼必須位於(或調用)[傳遞給'getJSON'的繼續](http://stackoverflow.com/questions/31129/how-can-i-return-a-variable-from-一個-的getJSON函數)。 – outis 2012-01-18 06:43:00

回答

0
var price = ""; 
$.getJSON("../JSONDeliveryPrice", null, function (data) { 
    price = eval(data.price); 
    console.log(price); // e.g. "$120", comes later 
    doSomething(data); // uses the JSON data 
}); 
console.log(price); // "", comes first 
+0

它不會起作用,因爲''console.log(price);'會在'getJSON'回調函數之前被調用mutch。 – Samich 2012-01-17 08:39:48

0

這並不是說你不能訪問回調函數以外的數據,它只是在console.log()執行語句執行前的回調,所以在執行日誌的時間,該變量仍然是空的。

我做a fiddle說明這個基於jQuery開發網站的例子