原生javascript實作AJAX的程式碼範例
javascript
web前端
這篇文章帶給大家的內容是關於原生javascript實作AJAX的程式碼範例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
原生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的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前
By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保護它?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)