我在一个对象中使用了一个回调函数来更新html(xmlhttprequest)。
第一次(onload),回调工作正常,第二次(timer1)在Post函数下,url属性未定义,控制台无错误。
我的脚本和一些控制台日志。
class PostJSON {
constructor() {
this.response = {};
this.url = "../iot/PostJSON.php";
}
callback = function() {
}
Post = function(datapost,callback) {
console.log(this.url);
console.log(datapost);
let xhttp = new XMLHttpRequest();
let myJSON = JSON.stringify(datapost);
xhttp.open("POST", this.url, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(myJSON);
var instance = this;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let json = JSON.parse(this.responseText);
instance.response = json;
instance.callback();
}
}
}
}```
const net = new PostJSON();
net.callback = function(){
console.log(this.response["data"]["datetime"][0]);
document.getElementById("temp").innerHTML = this.response["data"]["temp"][0] + "°C";
}
window.addEventListener('DOMContentLoaded', net.Post({"id":1}) );
var myTimer1 = setInterval(net.Post, 5000,{"x":1,"id":1});
function PostJSON() {
this.response = {};
this.url = "../iot/PostJSON.php";
this.callback = function() {
}
var that = this;
this.Post = function(datapost,callback) {
console.log(that.url);
console.log(datapost);
let xhttp = new XMLHttpRequest();
let myJSON = JSON.stringify(datapost);
xhttp.open("POST", that.url, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(myJSON);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let json = JSON.parse(this.responseText);
if (json.hasOwnProperty('infos'))
if (json["infos"].hasOwnProperty('infos'))
json["infos"]["infos"] = JSON.parse(json["infos"]["infos"]);
that.response = json;
that.callback();
}
}
}
}