2017-07-19 65 views
0

我想提取我的JSON数据并放入一个变量,这是从任何地方都可用。但我有一个错误信息,它说:食物是不确定的(警报排在最后)为什么这个构造函数不起作用? (在Ajax成功)

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); 

回答

1

刚刚尝试与关键字调用构造函数。它会工作。

foods = new foodConstructor(data[0]);

+1

谢谢,它的工作原理 –

+0

欢迎您 –

0

霍华德Fring的你会想要做的是移动警报到一个函数和从ajax请求成功时调用的回调函数中调用它。直到请求完成,才会填充food,这就是未定义的原因。例如:

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值。

1

你忘了new关键字

尝试:

  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); 
+0

,谢谢,我错过了新的关键字 –

+0

您的欢迎并没有什么问题 – user7951676

相关问题