如何在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
但它不起作用,仍然错误
P粉2810894852024-02-22 11:46:37
顺便说一句,我找到了解决方案,使用这个看起来有点棘手
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
存储到变量中,然后使用该变量调用其他方法。
有人有比这更好的解决方案吗?
谢谢
P粉4914214132024-02-22 11:36:54
您只需更新代码即可使用箭头函数,如下所示:
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", }); }, }