我想從使用Ajax通過jQuery同步加載的腳本中獲取對象。從同步jQuery加載的JS腳本中提取對象ajax調用
從這個劇本我試圖加載的對象,看起來像這樣從一個叫map_dropdowns.js
腳本,它返回對象options
:
{curr_cat: "RELATIONSHIP"
curr_subcat: " Population in households"
curr_total: "Total"}
我對與AJAX腳本代碼是在這裏:
<script>
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "script",
async: false,
success: function(data){
console.log(data);
}
});
console.log(options); //returns `Object{}` in the console, and only shows values when expanded
options["curr_cat"]; //returns undefined
console.log(Object.keys(options)); //returns an empty array []
</script>
在原始腳本中,options
中的鍵和值可以很好地訪問。 Chrome中的console.log
完全不顯示其內容(Object {curr_cat: "RELATIONSHIP", curr_subcat: " Population in households", curr_total: "Total"}
),而Object.keys()
工作得很好。
然而,在用Ajax函數將頁面加載到頁面後,嘗試使用鍵訪問這些值出現undefined
,Object.keys出現一個空數組[]
,而key:value對僅顯示在當我點擊對象時,控制檯顯示它,否則只顯示Object {}
。
我很確定我需要在Ajax的success
函數中做些什麼,但是我不確定經過大量的試驗和錯誤之後會發生什麼。
謝謝!
首先,請刪除'異步:FALSE' 。使用它是可怕的做法;直到瀏覽器實際上警告您在控制檯中使用它。其次,你說'Object.keys'和其他嘗試檢索值不起作用。您能否編輯您的問題以顯示您在這些情況下嘗試的代碼。 –
@RoryMcCrossan添加了那些!謝謝。我應該使用什麼而不是'async:false'來確保它是同步的? –
謝謝你,雖然我還是很困惑。 「選項」在哪裏定義?另外,只需刪除'async:false'並永遠不會使用同步請求。始終使用異步。 –