首页 > 代码库 > 原生JS Ajax 请求

原生JS Ajax 请求

       var username = document.getElementById(‘username‘).value;
            var password = document.getElementById(‘password‘).value;

            // 第一步:创建对象
            var xhr = null;
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            //初始化
            var url = ‘./check.php?username=‘+username+"&password="+password;
            xhr.open(‘post‘,url,false);
            //这段代码在xhr.send();执行完之后才能执行
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        alert(1);
                        var data =http://www.mamicode.com/ xhr.responseText;
                        if(data =http://www.mamicode.com/= 1){
                            document.getElementById(‘showInfo‘).innerHTML = ‘用户名或者密码错误‘;
                        }else if(data =http://www.mamicode.com/= 2){
                            document.getElementById(‘showInfo‘).innerHTML = ‘登录成功‘;
                        }
                    }
                };
            }

            xhr.send(null);

 

原生JS Ajax 请求