0
点赞
收藏
分享

微信扫一扫

ajax小结

guanguans 2022-02-15 阅读 165

ajax小结

1.什么是ajax

功能

  • 不刷新页面更新网页
  • 在页面加载后从服务器请求数据
  • 在页面加载后从服务器接收数据
  • 在后台向服务器发送数据

2.ajax原理(工作流程)

ajax是异步操作,假设·发起一个请求,向后台请求一个数据“apple”

  1. 点击按钮
  2. js:在浏览器中创建一个对象XmlHttpRequest(浏览器内置),用来存储数据
let xmlHttp = new XMLHttpRequest();
  1. 向后台发起请求
  2. 服务器:接收前端请求,把"apple"放入响应,写给前端,写入前端创建的XmlHttpRequest
 xmlHttp.open("GET", "http://localhost:8090/ajax-demo/ajax.action", true);
 xmlHttp.send();
  1. 前端也一直在监听此对象,看看对象状态是否有变化200,4
 xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  1. 前端从对象中获取数据,在其页面上重绘(更新)
document.getElementById("btnId").onclick=function(){

    let xmlHttp = new XMLHttpRequest();


    xmlHttp.onreadystatechange = function() { 
        if (this.readyState == 4 && this.status == 200) {
           let resVal =  this.responseText;
           document.getElementById("divId").innerText = resVal;
        }
      };

      xmlHttp.open("GET", "http://localhost:8090/ajax-demo/ajax.action", true);
      xmlHttp.send();

}
举报

相关推荐

0 条评论