无法读取数组上未定义的属性'push'

时间:2017-05-17 08:05:55

标签: jquery

为什么我会收到此错误:

  

无法读取未定义的属性'push'

好像我无法将数据推送到barcodes数组? console.log(data)有效。

var myScanObj = {
  $el: null,
  $res: null,
  $searchButton: null,
  $resetButton: null,
  $hiddenInput: null,
  $scanInput: null,
  $selectType: null,
  barcodes: [],
  init: function() {
    myScanObj.cacheDom();
    myScanObj.bindEvents();
  },
  cacheDom: function() {
    $el = $('.formControl');
    $res = $('#result');
    $searchButton = $el.find('#searchButton');
    $resetButton = $el.find('#resetButton');
    $hiddenInput = $el.find('input[name=hiddenField]');
    $scanInput = $el.find('input[name=myScan]');
    $selectType = $el.find('#myType');
  },
  bindEvents: function() {
    $searchButton.on('click', this.addBarcode.bind(this));
  },
  addBarcode: function() {
    var postForm = {
      'myType': $selectType.val(),
      'myScan': $hiddenInput.val()
    };
    $.ajax({
      url: "test.php",
      type: "POST",
      data: postForm,
      dataType: "text",
      success: this.successAjax
    });
  },
  showBarcode: function() {

  },
  successAjax: function(data) {
    this.barcodes.push(data);
    console.log(data);
  }
};

myScanObj.init();

这是我的test.php代码:

<?php
  $output = '';
  $output .= $_POST["myType"];
  $output .= $_POST["myScan"]; 
  echo $output
?>

2 个答案:

答案 0 :(得分:0)

你推的那一刻,

this.barcodes没有被记录下来。我认为this正在攻击ajax对象而不是myScanObj。

尝试:myScanObj.barcodes.push(data);

答案 1 :(得分:0)

问题是因为this函数中的successAjax是对AJAX调用中使用的jqXHR的引用,而不是myScanObj对象。

要解决此问题,您可以使用bind()

更改调用引用的范围
success: this.successAjax.bind(this)

或者,如果您不介意不支持旧版IE,请使用箭头功能:

success: data => this.successAjax(data)