When I use AJAX to post data to the server, I want to use this
in the onreadystatechange
function.
For example:
HTML
<div onclick=send.call(this)></div>
JavaScript
function send () {
this.style.background = "#ccc";
var xml = new XMLHttpRequest();
xml.open("post", "/post.php", true);
xml.send("data");
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
this.style.background = "#fff";
}
}.call(this);
}
I think it works, but when I use call
, the onreadystatechange
function only run once. When I use the code such as:
xml.onreadystatechange = function () {
console.log(xml.state);
}
the output is: 1 2 3 4
, but when I use
xml.onreadystatechange = function () {
console.log(xml.state);
}.call(this)
the output is: 1
Why?