原生javascript实现AJAX的方法

这篇文章主要介绍了原生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的方法
分享URL:http://lszwz.com/article/gghiec.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款