这就是我想做的事情:
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);
}
答案 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);
}