如何在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", }); }, }