AJAX基础

目录

零、码仙励志

一、什么是AJAX

二、readyState属性和onreadystatechange事件

三、XHR请求

1.GET请求

2.POST请求

四、同步与异步

五、XHR响应

1.responseXML

2.responseText

六、兼容问题


零、码仙励志

这个世界能轻而易举、毫不费力做到的,只有贫穷和衰老,其他的都需要努力

一、什么是AJAX

  1. AJAX(Asynchronous JavaScript and XML),最早出现在 2005 年的 Google Suggest,是在浏览器端进行网络编程(发送请求、接收响应)的技术方案,它使我们可以通过 JavaScript 直接获取服务端最新的内容而不必重新加载页面。让 Web 更能接近桌面应用的用户体验。
  2. 说白了,AJAX 就是浏览器提供的一套 API,可以通过 JavaScript 调用,从而实现通过代码控制请求与响应。实现网络编程。

二、readyState属性和onreadystatechange事件

  1. 当请求被发送到服务器时,我们需要执行一些基于响应的任务。
  2. 每当 readyState 改变时,就会触发 onreadystatechange 事件。
  3. readyState 属性存有 XMLHttpRequest 的状态信息。

 下面是 XMLHttpRequest 对象的三个重要的属性:

maxian.txt

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 是与服务器交换数据并更新部分网页的技术,在不重新加载整个页面的情况下
<script>
    //1. 创建一个 XMLHttpRequest 类型的对象 —— 相当于打开了一个浏览器
    var xhr = new XMLHttpRequest();
    //如果这个方法写到send()方法下面,监听不到状态1
    xhr.onreadystatechange = function () {
        console.log(this.readyState);
    };
    // 2. 打开与一个网址之间的连接 —— 相当于在地址栏输入访问地址
    xhr.open('GET', 'maxian.txt');
    // 3. 通过连接发送一次请求 —— 相当于回车或者点击访问发送请求
    xhr.send();
</script>

通过理解每一个状态值的含义得出一个结论:一般我们都是在 readyState 值为 4 时,执行响应的后续逻辑。

    xhr.onreadystatechange = function () {
        if (this.readyState === 4) {
            // 后续逻辑......
        }
    }
    xhr.onreadystatechange = function () {
        if(this.readyState==4){
            console.log(this.responseText)
        }
    };

三、XHR请求

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

 

1.GET请求

一个简单的 GET 请求:

time.php

<?php

echo time();

get.html

<body>
<script>
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'time.php');
    xhr.send();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
            console.log(this.responseText);
        }
    }
</script>
</body>

 

如果希望通过GET方法发送信息,请向URL添加信息:

time.php

<?php

header('Content-Type: application/json');
/**
 * 返回的响应就是一个 JSON 内容(返回的就是数据)
 * 对于返回数据的地址一般我们称之为接口(形式上是 Web 形式)
 */

// users.php?id=1 => id 为 1 的用户信息

$data = array(
  array(
    'id' => 1,
    'name' => '张三',
    'age' => 18
  ),
  array(
    'id' => 2,
    'name' => '李四',
    'age' => 20
  ),
  array(
    'id' => 3,
    'name' => '二傻子',
    'age' => 18
  )
);
if (empty($_GET['id'])) {
  // 没有 ID 获取全部
  // 因为 HTTP 中约定报文的内容就是字符串,而我们需要传递给客户端的信息是一个有结构的数据
  // 这种情况下我们一般采用 JSON 作为数据格式
  $json = json_encode($data); // => [{"id":1,"name":"张三"},{...}]
  echo $json;
} else {
  // 传递了 ID 只获取一条
  foreach ($data as $item) {
    if ($item['id'] != $_GET['id']) continue;
    $json = json_encode($item); // => [{"id":1,"name":"张三"},{...}]
    echo $json;
  }
}

get.html

<script>
    var xhr=new XMLHttpRequest();
    xhr.open('GET','users.php?id=2')
    xhr.send();
    xhr.onreadystatechange=function () {
        if (this.readyState==4){
            console.log(this.responseText);
        }
    }
</script>

 

2.POST请求

登陆案例

post.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AJAX发送POST请求</title>
  <style>
    #loading {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #555;
      opacity: .5;
      text-align: center;
      line-height: 300px;
    }

    #loading::after {
      content: '加载中...';
      color : #fff;
    }
  </style>
</head>
<body>
  <div id="loading"></div>
  <table border="1">
    <tr>
      <td>用户名</td>
      <td><input type="text" id="username"></td>
    </tr>
    <tr>
      <td>密码</td>
      <td><input type="password" id="password"></td>
    </tr>
    <tr>
      <td></td>
      <td><button id="btn">登录</button></td>
    </tr>
  </table>
  <script>

    // 找一个合适的时机,做一件合适的事情
    var btn = document.getElementById('btn')
    // 1. 获取界面上的元素 value
    var txtUsername = document.getElementById('username')
    var txtPassword = document.getElementById('password')
    var loading = document.getElementById('loading')

    btn.onclick = function () {
      loading.style.display = 'block'
      var username = txtUsername.value
      var password = txtPassword.value
      // 2. 通过 XHR 发送一个 POST 请求
      var xhr = new XMLHttpRequest()
      xhr.open('POST', 'login.php')
      // !!! 一定注意 如果请求体是 urlencoded 格式 必须设置这个请求头 !!!
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      // xhr.send('username=' + username + '&password=' + password)
      xhr.send(`username=${username}&password=${password}`)
      // 3. 根据服务端的反馈 作出界面提示
      xhr.onreadystatechange = function () {
        if (this.readyState !== 4) return
        console.log(this.responseText)
        loading.style.display = 'none'
      }
    }
  </script>
</body>
</html>

login.php

<?php

// 接收用户提交的用户名密码
if (empty($_POST['username']) || empty($_POST['password'])) {
  // echo ;
  exit('请提交用户名和密码');
}
// 校验
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === '123') {
  exit('恭喜你');
}

exit('用户名或者密码错误');
// 响应

四、同步与异步

  1. 关于同步与异步的概念在生活中有很多常见的场景,举例说明。
  2. 同步:一个人在同一个时刻只能做一件事情,在执行一些耗时的操作(不需要看管)不去做别的事,只是等待
  3. 异步:在执行一些耗时的操作(不需要看管)去做别的事,而不是等待

xhr.open() 方法第三个参数要求传入的是一个 bool 值,其作用就是设置此次请求是否采用异步方式执行,默认为 true ,如果需要同步执行可以通过传递 false 实现

<body>
  <script>
    var xhrAsync = new XMLHttpRequest();
    // open 方法的第三个参数是 async 可以传入一个布尔值,默认为 true
    xhrAsync.open('GET', 'maxian.txt', true);
    console.time('async');
    xhrAsync.send();
	//这里可能输入为空,因为是异步,上面的代码不一定执行完,readyState不一定为4
    console.log(xhrAsync.responseText);
    console.timeEnd('async');

    // 同步模式 ajax 操作会有楞等的情况
    // 区别在于 send 方法会不会出现等待情况
    var xhrSync = new XMLHttpRequest();
    // open 方法的第三个参数是 async 可以传入一个布尔值,默认为 true
    xhrSync.open('GET', 'maxian.txt', false);
    console.time('sync');
    xhrSync.send();
	//这里可能输入maxian.txt的内容,因为是同步,上面的代码一定执行完,readyState一定为4
    console.log(xhrSync.responseText);
    console.timeEnd('sync')
  </script>
</body>

五、XHR响应

1.responseXML

如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性

xml.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AJAX 请求 XML 格式的数据</title>
</head>
<body>
  <script>
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'xml.php')
    xhr.send()
    xhr.onreadystatechange = function () {
      if (this.readyState !== 4) return
      // this.responseXML 专门用于获取服务端返回的 XML 数据,操作方式就是通过 DOM 的方式操作
      // 但是需要服务端响应头中的 Content-Type 必须是 application/xml
	  console.log(this.responseXML.documentElement.innerHTML)
      console.log(this.responseXML.documentElement.children[0].innerHTML)
      console.log(this.responseXML.documentElement.getElementsByTagName('name')[0])
    }
  </script>
</body>
</html>

xml.php

<?php
header('Content-Type: application/xml');
?>
<?xml version="1.1" encoding="utf-8"?>
<person>
  <name>石羊</name>
  <age>16</age>
  <gender>男</gender>
</person>

 

2.responseText

responseText主要用于获得字符串形式的响应数据,前面已经用过很多次了,这里就不重复演示了,这里主要让它返回一个json格式的数据

json.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动态渲染数据到表格中</title>
</head>
<body>
<table>
    <tbody id="content"></tbody>
</table>
<script>
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'test.php')
    xhr.send()
    xhr.onreadystatechange = function () {
        if (this.readyState !== 4) return
        var res = JSON.parse(this.responseText)
        console.log("res",res)
        // res => 服务端返回的数据
        var data = res.data
        console.log("data",data)
        for (var i = 0; i < data.length; i++) {
            console.log(data[i])
        }
    }
</script>
</body>
</html>

test.php

<?php
header('Content-Type: application/json');
?>
{"success":true,"data":[
{"id":"1","name":"张三","age":"18"},
{"id":"2","name":"李四","age":"19"},
{"id":"3","name":"王五","age":"20"}
],"total_count":3}

六、兼容问题

var xmlhttp;
if (window.XMLHttpRequest)
{
    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
}
else
{
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

本篇博客来自于传智播客视频教程和菜鸟教程网站的总结以及笔记的整理,仅供学习交流,切勿用于商业用途,如有侵权,请联系博主删除,博主QQ:194760901

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值