我正在尝试提取我的json数据并将其放入一个变量中,该变量随处可见。但是我收到一条错误消息,它说:食物未定义(最后一行警报)
var foods;
function search() {
$.ajax({
url: "foodsrequest.php",
type: "GET",
dataType: "json",
async: false,
data: {"inputData": JSON.stringify(filterdata)},
success: function(data){
foods = foodConstructor(data[0]); ///yes, it is an array of objects and it has all the parameters needed
function foodConstructor(dataIn){
this.id = dataIn.id;
this.name = dataIn.name;
this.price = dataIn.price;
this.species = dataIn.species;
this.type = dataIn.type;
this.manufacturer = dataIn.manufacturer;
this.weight = dataIn.weight;
this.age = dataIn.age;
this.partner = dataIn.partner;
}
}
});
}
alert(foods.name);
最佳答案
只需尝试使用new关键字调用您的构造函数。会的。foods = new foodConstructor(data[0]);