原生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的代码示例的详细内容。
