how to call another method inside 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",
});
},
}
i have try to using this.calert
but it doesn't work, still error
CodePudding user response:
You simply need to update your code to use arrow functions, as follows:
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",
});
},
}
Or alternatively, store a local reference to the method, like:
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",
});
},
}
CodePudding user response:
btw i found the solution, looks like little bit tricky using this
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",
});
},
}
i store the this
to variable and then i use the variable to call another methods.
Anyone have any solutions better than this?
Thanks