2017-07-19 19 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は要求が完了するまで入力されないため、未定義です。たとえば:バック食べ物後successコールでfoodAlertを呼び出すことにより、

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

は示さfood.nameの値とアラートを開きます人口です。

1

新しいキーワードに

てみてください忘れてしまった:

  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

関連する問題