AJAX - 基本流程和特点
- <script>
- window.onload = function(ev){
- var oBtn = document.querySelector(\'button\');
- // querySelector https://segmentfault.com/q/1010000014291684
- oBtn.onclick = function(ev1){
- // 1. 创建异步对象
- var xmlHttp = new XMLHttpRequest();
- /* 2. 设置请求方式和请求地址 open(method,url,async)
- method: 请求的类型 GET 或 POST
- url: 文件在服务器上的位置
- async: true(异步) false(同步)
- */
- xmlHttp.open("GET", "04-ajax-get.php", true);
- // 3. 发送请求
- xmlHttp.send();
- // 4. 监听状态的变化
- xmlHttp.onreadystatechange = function(ev2){
- /*
- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4:请求已完成,且相应已就绪
- */
- if(xmlHttp.readyState === 4){
- //判断是否请求成功
- if(xmlHttp.status >= 200 && xmlHttp.status < 300 || xmlHttp.status === 304){
- // 5. 处理返回的结果
- console.log(\'接收到服务器返回的数据\');
- }else{
- console.log(\'没有接收到服务器返回的数据\');
- }
- }
- }
- }
- }
- </script>
- </head>
- <!-- 使用Ajax更新数据和 不使用Ajax的区别:
- 不使用ajax更新数据,会重新加载整个页面
- (例如 淘宝 输入关键字,搜索)
- 使用ajax更新数据, 不会重新加载整个页面,只更新某些部分
- (例如 淘宝搜索栏- 输入关键字 自动更新下拉提示框的内容 )-->
- <body>
- <button>发送请求</button>
- </body>