RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
原生javascript实现AJAX的方法-创新互联

这篇文章主要介绍了原生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的方法内容对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,遇到问题就找创新互联,详细的解决方法等着你来学习!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享题目:原生javascript实现AJAX的方法-创新互联
链接分享:http://sczitong.cn/article/ipohd.html