为什么我会收到此错误:
无法读取未定义的属性'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
?>
答案 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)