如何在 Javascript 中使用 .bind 时获取 XMLHttpRequest responseText?

How to get XMLHttpRequest responseText while using .bind in Javascript?

这是我想做的事情:

response: string;
sendCreateInvoice(invoice, job){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.response = this.responseText;
    };
  };
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

所以我认为我需要使用 .bind(this),但是当我这样做时,我似乎无法再访问 this.responseText。我试过这样:

response: string;
sendCreateInvoice(invoice, job){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.response = this.responseText;
    };
  }.bind(this);
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

我尝试了 this.xmlhttp.responseTextxmlhttp.responseText 但没有成功。我哪里错了?如何将 responseText 保存到 response

==================

工作代码:

response: string;
sendCreateInvoice(){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = () => {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      this.response = xmlhttp..responseText;
    };
  };
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

不要使用 bind 只是将 this 的值存储在函数外部的变量中,因为您正在使用 this 作为函数内部的请求!像这样:

response: string;
sendCreateInvoice(invoice, job){
  var that = this; // <<<< store it here

  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      that.response = this.responseText;
  //  ^^^^ use it here
    };
  };

  // these two lines should be outside of the callback of the event listener
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

您可以使用 xmlhttp 来引用 XMLHttpRequest 对象。

并且对 open()send() 的调用需要在回调函数之外。

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      this.response = xmlhttp.responseText;
    };
  }.bind(this);

此外,您可以使用箭头函数代替 .bind(this)

  xmlhttp.onreadystatechange = () => {
    if (this.readyState == 4 && this.status == 200) {
      this.response = xmlhttp.responseText;
    };
  };
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);

箭头函数将 this 视为普通词法变量。