weixin_33671935 2014-08-22 03:30 采纳率: 0%
浏览 76

如何将readyState设置为200?

我希望通过以下方法处理所有Ajax请求:

XMLHttpRequest.prototype.send=function(body){
  var myResponse='myResponse';
  Object.defineProperty(this,'responseText',{
    get:function(){
      return res
    }
  });
  Object.defineProperty(this,'readyState',{
    get:function(){
       return 4
    }
  });
  Object.defineProperty(this,'status',{
     get:function(){
       return 200
    }
  });
  this.onreadystatechange();
};

在输出中,responseText和readyState成功实现了我想要的结果。但是Chrome给了我这个错误:

Uncaught InvalidStateError: Failed to read the 'status' property from 'XMLHttpRequest': the object's state must not be OPENED.

我知道我需要将readyState设置为200,这样网页的其他部分就可以正常运行。但我不知道怎么能做到......任何建议都将不胜感激!

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-02 12:25
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    你已经正确地设置了readyState属性。如果你希望在发送请求时将其设置为200,请确保在调用send()之前设置readyState。

    以下是修改后的代码:

    XMLHttpRequest.prototype.send = function (body) {
      var self = this;
      // 设置 readyState
      self.readyState = 1; // 未打开
    
      // 调用 send 方法
      self.send(body);
    };
    
    // 测试 XMLHttpRequest.prototype.send()
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      console.log(xhr.responseText); // 输出 responseText 的值
      console.log(xhr.readyState); // 输出 readyState 的值
      console.log(xhr.status); // 输出 status 的值
    };
    xhr.open('GET', '/your-url');
    xhr.send();
    

    在这个例子中,我们首先设置 readyState 为 1(未打开),然后在 send() 方法中调用它。这应该解决 Chrome 中出现的问题。

    评论

报告相同问题?