3 javascript ajax jquery this object-literal
我有一个对象文字router,包含一个 ajax 调用。我想this.printMovies()在ajax调用中调用其他函数但this引用ajax对象。
我如何转义它并this引用router对象本身?
var router = {
//...
init : function() {
this.getData("api/movies", "movies", callback);
},
getData : function (url, htmlType, callback) {
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); //'this' refers to ajax
this.printMovies(response, callback).bind(this) //still doesn't work
}
},
error: function (response) { console.log("Error:" + response); }
});
},
printMovies : function(){
},
}
Run Code Online (Sandbox Code Playgroud)
将context选项传递给 ajax:
$.ajax({
context: this,
/* other options */
}
Run Code Online (Sandbox Code Playgroud)
现在在 ajax 回调中,this将引用router对象。