API

1-1 如何使用ajax

  • 1-1 HTML和CSS实现页面
  • 1-2 Ajax和Web服务器进行数据的异步交换
  • 1-3 运用JS操作DOM实现动态的局部刷新

    1-2 实现ajax

    1. var banner = 'http://47.108.197.28:3000/banner'
    2. /* 1、创建ajax的核心对象 */
    3. var xhr = new XMLHttpRequest();
    4. /* 2、需要与服务器建立连接 */
    5. xhr.open("get", url, true)
    6. /* 3、发送请求 */
    7. xhr.send();
    8. /* 4、响应数据 */
    9. /* onreadystatechange监听服务器状态的变化 */
    10. xhr.onreadystatechange = function () {
    11. // readystate值代表服务器响应的变化 ==4 请求完成,响应准备就绪
    12. /* status==200请求成功,数据成功的响应 */
    13. if (xhr.readyState == 4 && xhr.status == 200) {
    14. var res = JSON.parse(xhr.responseText)
    15. console.log(res)
    16. }
    17. }

    1-2-1 Ajax核心对象

    1. var xhr = new XMLHttpRequest();

    1-2-2 与服务器建立连接

    1. xhr.open('get',url,true)

    1-2-3 发送请求

    1. xhr.send();

    1-2-4 服务器响应

    1. xhr.onreadystatechange = function(){
    2. if(xhr.readyState == 4 && xhr.status == 200){
    3. var txt = JSON.parse(xhr.responseText);
    4. console.log(txt);
    5. }
    6. }
    1. ● responseText:获取字符串形式的响应数据
    2. ● status:以数字形式返回http的状态码
    3. ● readystate值代表服务器响应的变化
    image.png
    image.png

    2-1 XMLHttpRequest 对象

    2-1-1 创建 XMLHttpRequest 对象

    1. variable = new XMLHttpRequest();

    2-1-2 XMLHttpRequest 对象方法

    | 方法 | 描述 | | —- | —- | | new XMLHttpRequest() | 创建新的 XMLHttpRequest 对象 | | abort() | 取消当前请求 | | getAllResponseHeaders() | 返回头部信息 | | getResponseHeader() | 返回特定的头部信息 | | open(method, url, async, user, psw) | 规定请求
    - method:请求类型 GET 或 POST
    - url:文件位置
    - async:true(异步)或 false(同步)
    - user:可选的用户名称
    - psw:可选的密码
    | | send() | 将请求发送到服务器,用于 GET 请求 | | send(string) | 将请求发送到服务器,用于 POST 请求 | | setRequestHeader() | 向要发送的报头添加标签/值对 |

2-1-3 XMLHttpRequest 对象属性

属性 方法
onreadystatechange 定义当 readyState 属性发生变化时被调用的函数
readyState 保存 XMLHttpRequest 的状态。
- 0:请求未初始化
- 1:服务器连接已建立
- 2:请求已收到
- 3:正在处理请求
- 4:请求已完成且响应已就绪
responseText 以字符串返回响应数据
responseXML 以 XML 数据返回响应数据
status 返回请求的状态号
- 200: “OK”
- 403: “Forbidden”
- 404: “Not Found”

如需完整列表请访问 Http 消息参考手册 | | statusText | 返回状态文本(比如 “OK” 或 “Not Found”) |