如何在jquery ajax中调用另一个方法?
methods : {
calert(type,msg="",error=""){
console.log("call me");
},
getData(){
$.ajax({
type: "GET",
success: function(data){
// error calert not found
calert(true,"","asd");
},
error: function (error) {
// also error calert not found
this.calert(false,"",error);
},
complete: function(){
},
url: "/test",
});
},
}
我尝试使用 this.calert 但它不起作用,仍然错误
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
顺便说一句,我找到了解决方案,使用这个看起来有点棘手
methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ let vm = this; $.ajax({ type: "GET", success: function(data){ // error calert not found vm.calert(true,"","asd"); }, error: function (error) { // also error calert not found vm.calert(false,"",error); }, complete: function(){ }, url: "/test", }); }, }我将
this存储到变量中,然后使用该变量调用其他方法。有人有比这更好的解决方案吗?
谢谢
您只需更新代码即可使用箭头函数,如下所示:
methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: (data) => { this.calert(true,"","asd"); }, error: (error) => { this.calert(false,"",error); }, complete: (){ }, url: "/test", }); }, }或者,存储对该方法的本地引用,例如:
methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ const { calert } = this; $.ajax({ type: "GET", success: function(data){ // error calert not found calert(true,"","asd"); }, error: function (error) { // also error calert not found calert(false,"",error); }, complete: function(){ }, url: "/test", }); }, }