HTTP 客户端可用于执行 AJAX 请求并使用 GET 和 POST 请求动态更新页面内容。
该类可以这样使用:
httpClient = new http_client(); httpClient.get("/api/request-headers", function (response) { document.getElementById("_id_of_element").innerText = response; });
在 onitroad 上使用时,不需要实例化该类,因为它是由系统自动加载的。
相反,作者可以直接使用它:
httpClient.get("/api/time/date", function (response) { document.getElementById("_id_of_element").innerText = response; });
要在 onitroad 上的文章中使用 HTTP 客户端,我们只需在文章的代码中使用 HTML 脚本元素。
JavaScript HTTP 客户端
class http_client { constructor() { this.response = false; } post(URL = 'required', postData = false, callBack = false) { this.newXMLHttp(callBack); this.xmlhttp.open('POST', URL, true); this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.xmlhttp.send(postData); }; get(URL = 'required', callBack = false) { this.newXMLHttp(callBack); this.xmlhttp.open('GET', URL, true); this.xmlhttp.send(); }; newXMLHttp(callBack) { this.xmlhttp = new XMLHttpRequest(); this.xmlhttp.onreadystatechange = () => { if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) { this.shouldWeCallBack(callBack); } }; } shouldWeCallBack(callBack) { //Sometimes we may need to return the response body //Also note that many situations are best handled on the server-side, //in which case we may rely on the response to tell a user what went wrong. if (callBack !== false) { //The callBack function contains the actions //to perform after loading the response. //It is passed to the get() method from the calling block callBack(this.xmlhttp.responseText); } else { return true; //If not returning the response, return true } } }
日期:2020-06-02 22:17:28 来源:oir作者:oir