我有以下用javascript编写的代码,
var submit = {
preloader_id: "",
send:function (form_id) {
var url = $(form_id).attr("action");
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success:(result) => {
},
error: function(result) {
// Some errors
},
beforeSend: function() {
console.log(this.preloader_id);
if (this.preloader_id != "") {
run_preloader(this.preloader_id);
}
},
completes: function() {
if (this.preloader_id != "") {
run_preloader(this.preloader_id, 'true');
}
}
});
}
}是这样叫的
submit.preloader_id = "form-id";
submit.send('div#some-id');问题是当我试图在这个方法中获得在preloader_id中分配的值时
beforeSend: function() {
console.log(this.preloader_id); // look if there is id name to fetch
if (this.preloader_id != "") {
run_preloader(this.preloader_id);
}
},我搞不清楚,
如何在ajax中获取submit.preloader_id = "div#some-id";在beforesend方法中的值?
发布于 2016-07-04 08:48:34
这个问题是因为this的作用域在$.ajax的beforeSend处理程序中发生了变化。若要解决此问题,请将引用存储在处理程序之外:
var submit = {
preloader_id: "",
send:function (form_id) {
var _this = this; // store here
var url = $(form_id).attr("action");
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success:(result) => {},
error: function(result) {
// Some errors
},
beforeSend: function() {
// use here...
console.log(_this.preloader_id);
if (_this.preloader_id != "") {
run_preloader(_this.preloader_id);
}
},
completes: function() {
// and here...
if (_this.preloader_id != "") {
run_preloader(_this.preloader_id, 'true');
}
}
});
}
}发布于 2016-07-04 08:49:04
this指的是错误的上下文。在您的var that = this方法中添加send并通过它引用preloader_id:that.preloader_id
https://stackoverflow.com/questions/38180293
复制相似问题