温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

原生javascript实现AJAX的方法

发布时间:2020-10-20 16:12:37 来源:亿速云 阅读:135 作者:小新 栏目: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的方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI