原生JavaScript的ajax方法——请求数据

1、使用nodejs配置本地服务器

 window.function () {
                getData()
            }

2、在浏览器运行程序,并发送数据请求

3、在路由中拦截请求,调用控制器中相应方法getStuData,返回数据

router.get("/student.do",stuCtrl.getStuData)

4、使用ajax获得数据

function getData() {
                // 获取ajax对象
                if(window.XMLHttpRequest){
                    var xhr=new XMLHttpRequest();//DOM获取ajax对象的方法
                }else{
                    var xhr=new ActiveXObject("Microsoft.XMLHTTP");//ie获取ajax对象的方法
                }
                // 打开ajax对象参数(1.请求方式 2.请求地址 3.同步(false)或者异步(true)
                xhr.open("get","/student.do",true);
                // 利用ajax对象发送数据
                xhr.send();
                // ajax请求结束所触发的事件
                xhr.onreadystatechange=function () {//回调函数
                    if(xhr.readyState==4&&xhr.status==200){
                        console.log("响应完毕");
                        //获得数据,并转为JSON格式
                        let stuArr=JSON.parse(xhr.responseText);  
                        //进行其他的数据操作
                        ......
                    }
               }
    		}    

猜你喜欢

转载自blog.csdn.net/weixin_39150852/article/details/85770225