如何在 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但它不起作用,仍然錯誤
uj5u.com熱心網友回復:
您只需更新代碼以使用箭頭函式,如下所示:
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",
});
},
}
uj5u.com熱心網友回復:
順便說一句,我找到了解決方案,使用它看起來有點棘手
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到變數,然后我使用該變數來呼叫另一個方法。
有人有比這更好的解決方案嗎?
謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439716.html
