重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章主要介紹了原生javascript實現AJAX的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
創新互聯公司長期為上1000+客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為雷山企業提供專業的成都網站設計、成都網站制作,雷山網站改版等技術服務。擁有十年豐富建站經驗和眾多成功案例,為您定制開發。
原生JS使用AJAX使用代碼,代碼如下
var xhr1 = new XMLHttpRequest; xhr1.open("POST", 'http://47.92.121.171:17788', true); xhr1.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr1.onreadystatechange = function () { if (xhr1.readyState == 4 && xhr1.status == 200) { console.log("打印用戶信息1" + xhr1.responseText); } } xhr1.send("code=p_001&name=aaaaaa&pas=123456&belong=aabbccdd");
如果需要ajax運行方法完成后調用結果的話 需要使用回調函數 或者 promise
回調函數
private loadXMLDoc(url, sendcode, cfunc) { this.xmlhttp = new XMLHttpRequest; this.xmlhttp.open("POST", url, true); this.xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); this.xmlhttp.onreadystatechange = cfunc; this.xmlhttp.send(sendcode); } private myFunction() { this.loadXMLDoc("http://47.92.121.171:17788", "code=p_001&name=aaaaaa&pas=123456&belong=aabbccdd",()=>{ if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) { console.log("3") console.log("打印用戶信息1" + this.xmlhttp.responseText) } }); }
使用promise
this.getGameServer().then(function (res) { console.log("res" + res); }).catch(function (rej) { console.log("rej" + rej); });private getGameServer() { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.open("POST", 'http://47.92.121.171:9002/rout/get_game_servers', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { resolve(xhr.responseText); } } xhr.send("game=1&shang=common"); }); }
感謝你能夠認真閱讀完這篇文章,希望小編分享原生javascript實現AJAX的方法內容對大家有幫助,同時也希望大家多多支持創新互聯,關注創新互聯行業資訊頻道,遇到問題就找創新互聯,詳細的解決方法等著你來學習!