我在原型的Ajax.Request类中获取正确的范围时遇到了麻烦.我要做的是编写一个包含ajax请求的简单API:
API = Class.create({ initialize:function(api_token) { this.api_token = api_token; this.request_uri = new Template('/api/#{api_token}/#{resource}.json'); this.status = 0; this.last_result = null; }, some_api_call:function() { var result = this._request('resource', {'id':1}); // and so on... }, _request:function(resource, params) { var uri = this.request_uri.evaluate({"api_token":this.api_token,"resource":resource}); new Ajax.Request(uri, { contentType:'application/json', method:'get', parameters:params, onSuccess:function(r) { alert(this); this.last_result = r.responseJSON; this.status = r.status; } }); return this.last_result; } });
当我在onSuccess()方法中时,我期望+ this +来引用父对象,但是它给了我DOMWindow.我似乎无法将响应数据放入API类中.我认为这是一个愚蠢的事情(绑定?),但我今天似乎无法想到这一点.
谢谢
好的.我错过了更大的问题.我请求异步所以它被设置的结果,只是没有马上.公平地说,这也是一个具有约束力的问题.这是正确的要求:
_request:function(resource, params) { var uri = this.request_uri.evaluate({"api_token":this.api_token,"resource":resource}); new Ajax.Request(uri, { asynchronous: false, contentType:'application/json', method:'get', parameters:params, onSuccess:function(r) { this.last_result = r.responseJSON; this.status = r.status; }.bind(this) }); alert(this.status); return this.last_result; }