[英]Returning variables inside JS / JSON functions
我試圖了解JS中的JSON,回調等。 在下面的示例中,您將看到我在$ .getJSON的函數回調中。 然后,我進入getSomething()並期望它改變我的結果變量。 它會在功能范圍內更改它,但是當我跳出該功能時不會更改它。
您將從2 console.log()看到第一個顯示正確,而第二個顯示不正確。 我確定問題的答案與通過返回變量有關。 回調,但有人可以啟發
我 :)
謝謝!
碼:
$.getJSON('/cart.js', function (cart, textStatus) {
var result = '';
result += 'Sample Stuff';
StackOverflow.getSomething(param1, param2, function(a, b) {
for(j=0; j < b.length; j++) {
if (b.options[j] != 'Default Title') {
if (a.options[j].name.indexOf("Color") > -1) {
result += b.options[j].name;
console.log(result); // <-- It comes out correct (Sample Stuff + b.options...)
}
}
}
});
console.log(result); // <-- It comes out incorrect, just (Sample Stuff)
});
我猜StackOverflow.getSomething()
運行一個AJAX請求嗎? 因此,在AJAX請求完成之前,不會執行其回調(通過a
和b
循環)中定義的內容。 發生的情況是,將觸發StackOverflow.getSomething
,然后在代碼末尾立即執行console.log(result)
。 到那時,尚未運行StackOverflow.getSomething
的回調,並且尚未更新result
。 僅記錄“樣本內容”。 但是,當第二個console.log在( getSomething
)AJAX請求之后在回調中執行時, result
被更新並“正確”記錄。
換句話說,執行順序是這樣
result
設置為“樣本內容” StackOverflow.getSomething()
使用附加的回調函數觸發AJAX請求 console.log(result)
記錄“樣本內容” a
和b
相應地更新result
console.log(result)
記錄的終值result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.