I would make a jquery function that import a json value and return an array when we call it. I coded the following function but the returned array is empty.
我将创建一个jquery函数,该函数导入json值并在调用它时返回数组。我编写了下面的函数,但是返回的数组是空的。
The json file is very basic like this example :
json文件非常基本,如下例所示:
{
"fruit": [ "babana", "pineapple", "apple" ],
"vegetable" : [ "salad", "carrot", "tomato" ]
}
I call my json with the following function
我使用以下函数调用json
$( function() {
var fruit = new Array();
var vegetable = new Array();
var food = new Array();
function loadJson(result) {
$.getJSON('myfile.json', function (data) {
fruit = data.fruit;
vegetable = data.vegetable;
})
.error(function() {
console.log('error: JSON not loaded');
})
.done(function() {
//console.log( "JSON loaded!" );
var food = fruit.concat(vegetable);
return result;
});
}
After I call this function in another function with
我把这个函数命名为另一个函数。
loadJson(food); loadJson(fruit);
Can you help me?
你能帮我吗?
1 个解决方案
#1
0
I think this is what you're looking for, I've fired mine on document ready just so I could test the function quickly, but you should give you the result you're after.
我想这就是你要找的,我已经把我的文档准备好了,这样我可以快速地测试函数,但是你应该给你你想要的结果。
Answer Updated:
回答更新:
function loadJson( type ) {
var final_result = null;
$.ajax({
type: 'GET',
url: "test.json",
async: false,
dataType: "json",
success: function (data) {
var fruit = data['fruit'],
vegetable = data['vegetable'],
food = fruit.concat(vegetable),
result = food;
switch( type ) {
case 'fruit':
result = fruit;
break;
case 'vegetable':
result = vegetable;
break;
case 'food':
result = food;
break;
}
final_result = result;
}
});
return final_result;
}
$( document ).ready(function() {
loadJson( 'food' );
loadJson( 'fruit' );
loadJson( 'vegetable' );
var test = loadJson( 'fruit' );
console.log( test );
});
#1
0
I think this is what you're looking for, I've fired mine on document ready just so I could test the function quickly, but you should give you the result you're after.
我想这就是你要找的,我已经把我的文档准备好了,这样我可以快速地测试函数,但是你应该给你你想要的结果。
Answer Updated:
回答更新:
function loadJson( type ) {
var final_result = null;
$.ajax({
type: 'GET',
url: "test.json",
async: false,
dataType: "json",
success: function (data) {
var fruit = data['fruit'],
vegetable = data['vegetable'],
food = fruit.concat(vegetable),
result = food;
switch( type ) {
case 'fruit':
result = fruit;
break;
case 'vegetable':
result = vegetable;
break;
case 'food':
result = food;
break;
}
final_result = result;
}
});
return final_result;
}
$( document ).ready(function() {
loadJson( 'food' );
loadJson( 'fruit' );
loadJson( 'vegetable' );
var test = loadJson( 'fruit' );
console.log( test );
});