2017-04-08 41 views
0

這就是我想要做的:如何在Javascript中使用.bind時獲取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); 
} 
+1

'xmlhttp.responseText'應該已經工作了。也許你忘了'xmlhttp.readyState'和'xmlhttp.status'? – Barmar

回答

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作爲一個正常的詞法變量。

+0

@ibrahimmahrir看到我更新的措辭。 – Barmar

+0

它的工作!箭頭功能做到了。我不知道爲什麼。我沒有嘗試'that'方法,因爲我不喜歡額外的步驟:)謝謝你們! – Jus10

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); 
} 
+0

是的,打開和發送只是一個錯字,我會編輯它。感謝您的迴應! – Jus10

相關問題