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

时间:2017-04-08 00:05:48

标签: javascript xmlhttprequest 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;
    };
  };
  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);
}

2 个答案:

答案 0 :(得分:2)

您可以使用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视为正常的词法变量。

答案 1 :(得分:1)

不要使用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);
}