2017-07-19 54 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

相關問題