[英]Get data from local json file in Vuejs method using jQuery $.getJSON()
[英]Using Jquery to get JSON objects from local file
我正在嘗試使用Jquery從本地文件中獲取JSON對象(產品)列表,並將所有對象存儲在名為allItems的單個數組中。 該文件與代碼位於同一目錄中,並稱為“allItems.json”。 我現在就是這樣做的:
function getAllSupportedItems(){
var allItems = new Array();
$.getJSON("allItems.json",
function(data){
$.each(data.items,
function(item){
allItems.push(item);
});
});
return allItems;
}
基於此示例: http : //api.jquery.com/jQuery.getJSON/
為了使getAllSupportedItems
能夠返回任何項,AJAX調用需要同步運行。
getJSON
轉換為以下異步調用:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
異步是默認值。 因此,您需要明確地將您的請求更改為同步請求:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
async: false
});
另一種方法是重新考慮使用getAllSupportedItems
並將其變為異步實用程序的方式:
function getAllSupportedItems(callback){
$.getJSON("allItems.json",
function(data){
var allItems = [];
$.each(data.items,
function(item){
allItems.push(item);
});
callback(allItems);
// callback(data.items); should also work
});
}
當我最初寫這個答案時,jQuery沒有內置的Deferred支持。 今天做這樣的事情更加簡潔靈活:
function getAllSupportedItems( ) {
return $.getJSON("allItems.json").then(function (data) {
return data.items;
});
}
// Usage:
getAllSupportedItems().done(function (items) {
// you have your items here
});
你好嗎? 如果你期望main函數(“getAllSupportedItems”) 返回你所做的數組,那么這將無效。 $.getJSON
函數是異步的 ,因此處理程序在外部函數返回之前不會實際構建數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.