這就是我想要做的:如何在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.responseText
和xmlhttp.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);
}
'xmlhttp.responseText'應該已經工作了。也許你忘了'xmlhttp.readyState'和'xmlhttp.status'? – Barmar