Prototype和Ajax.Request范围

时间:2009-05-21 15:59:40

标签: javascript ajax prototypejs

我在原型的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类中。我认为这是愚蠢的(绑定?),但我今天似乎无法想到这一点。

由于

2 个答案:

答案 0 :(得分:8)

好。我错过了更大的问题。我是异步请求所以 设置结果,而不是立即。公平地说,这也是一个具有约束力的问题。这是正确的要求:

_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;
}

答案 1 :(得分:0)

您的解决方案不起作用?

您需要在嵌套函数上方使用局部变量,然后将它们转换为'this'范围:

 _request:function(resource, params)
    {
      var uri = this.request_uri.evaluate({"api_token":this.api_token,"resource":resource});
      var last_result = "";
      var status = "";
      new Ajax.Request(uri,
      {
        asynchronous: false,
        contentType:'application/json',
        method:'get',
        parameters:params,
        onSuccess:function(r)
        {
          last_result = r.responseJSON;
          status = r.status;
        }
      });  
      this.last_result = last_result;
      this.status = status;  
      alert(this.status);
      return this.last_result;
    }