這篇文章主要介紹了原生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的方法內容對大家有幫助,同時也希望大家多多支持創新互聯,關注創新互聯行業資訊頻道,遇到問題就找創新互聯,詳細的解決方法等著你來學習!
文章名稱:原生javascript實現AJAX的方法
標題網址:http://vcdvsql.cn/article42/gghiec.html
成都網站建設公司_創新互聯,為您提供外貿建站、外貿網站建設、小程序開發、網站設計公司、自適應網站、服務器托管
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯