Javascript 为什么这个构造函数不起作用?(在Ajax成功中)
我试图提取我的json数据并将其放入一个变量中,该变量可以从任何地方获得。但我收到了一条错误消息,它说:食品未定义(最后一行警告)Javascript 为什么这个构造函数不起作用?(在Ajax成功中),javascript,jquery,ajax,object,constructor,Javascript,Jquery,Ajax,Object,Constructor,我试图提取我的json数据并将其放入一个变量中,该变量可以从任何地方获得。但我收到了一条错误消息,它说:食品未定义(最后一行警告) Howard Fring您要做的是将警报移动到一个函数中,并从ajax请求成功时调用的回调函数中调用它食物在请求完成之前不会填充,这就是它未定义的原因。例如: var foods; function search() { $.ajax({ url: "foodsrequest.php", type:
Howard Fring您要做的是将警报移动到一个函数中,并从ajax请求成功时调用的回调函数中调用它<代码>食物在请求完成之前不会填充,这就是它未定义的原因。例如:
var foods;
function search() {
$.ajax({
url: "foodsrequest.php",
type: "GET",
dataType: "json",
async: false,
data: {"inputData": JSON.stringify(filterdata)},
success: function(data){
foods = new 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;
}
foodAlert();
}
});
}
function foodAlert(){
alert(foods.name);
}
通过在
success
中调用foodAlert
,食物填充后回调将打开一个警报,显示值为food.name
。Howard Fring您要做的是将警报移动到一个函数中,并从ajax请求成功时调用的回调函数调用它<代码>食物在请求完成之前不会填充,这就是它未定义的原因。例如:
var foods;
function search() {
$.ajax({
url: "foodsrequest.php",
type: "GET",
dataType: "json",
async: false,
data: {"inputData": JSON.stringify(filterdata)},
success: function(data){
foods = new 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;
}
foodAlert();
}
});
}
function foodAlert(){
alert(foods.name);
}
通过在
success
中调用foodAlert
,食物填充后回调将打开一个警报,显示food.name
值。您忘记了新关键字
尝试:
你忘了新的关键字 尝试:
只需尝试使用new关键字调用构造函数。它会起作用的
foods=newfoodconstructor(数据[0])代码>只需尝试使用new关键字调用构造函数。它会起作用的
foods=newfoodconstructor(数据[0])代码>
foods = new 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 );