为什么这个构造函数不起作用? (在Ajax成功)

时间:2017-07-19 21:42:46

标签: javascript jquery ajax object constructor

我正在尝试提取我的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);

3 个答案:

答案 0 :(得分: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 ); 

答案 1 :(得分:1)

尝试使用 new 关键字调用构造函数。它会起作用。

foods = new foodConstructor(data[0]);

答案 2 :(得分:0)

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

在填充食物后,在foodAlert回拨中致电success会打开一个显示food.name值的提醒。