您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

原生javascript实现AJAX的代码示例

2024/5/19 7:41:48发布16次查看
本篇文章给大家带来的内容是关于原生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的代码示例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product