ajax工作流程

1.ajax工作流程

1.1几种访问服务器的方式

/* 前端访问服务器的几种方式

1.直接在地址输入url

2.HTML:a标签的href

3.js:window.location.href=''

4.ajax: 在网页不跳转的情况下,向服务器发送请求

*/

1.2 ajax的工作流程

/* 前后端交互三个流程

      1.请求 2.处理 3.响应

     

      1.ajax技术: 在网页不刷新的情况下,向服务器发送请求数据

          ajax技术作用:局部刷新

      2.XMLHttpRequest对象:负责实现ajax技术的对象

          (1)创建xhr对象(小黄人对象)

            let xhr=new XMLHttpRequest()

          (2)设置请求方法和地址

            xhr.open('请求方法','请求地址')

          (3)发送请求

            xhr.send()

          (4)注册响应完成事件

            xhr.οnlοad=function(){ xhr.responseText }

      */

2.get请求与post请求

2.1 get请求提交参数

/* get与post区别:传参方式不同

          (1)get参数:直接在url后面拼接

            *格式:url?key=value

*/

// (1)创建xhr对象
    let xhr=new XMLHttpRequest()
      // (2)设置请求方法和地址
      xhr.open('get','https://autumnfish.cn/api/joke/list?num=10')
      // (3)发送请求
      xhr.send()
      // (4)注册响应事件
      xhr.onload=function(){
        // 获取服务器响应数据
        console.log(xhr.responseText)
        // 实际开发中,服务器一般会返回json格式字符,前端需要把json->js
        let res=JSON.parse(xhr.responseText)
        console.log(res)
      }

2.2 post请求提交参数

/* get与post区别:传参方式不同

          (1)get参数:直接在url后面拼接

            *格式:url?key=value

          (2)post参数:需要两个步骤

             (2.1)post需要设置请求头:这是一个固定格式,建议cv

                xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')

             (2.2)post参数要在send中发送

                xhr.send('key=value')

      */

// (1)创建xhr对象
    let xhr=new XMLHttpRequest()
      // (2)设置请求方法和地址
      xhr.open('post','https://autumnfish.cn/api/user/register')
      // (3)设置请求头:只有post请求才需要
      xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
      // (4)发送请求
      xhr.send('username=asdfg')
      // (5)注册响应事件
      xhr.onload=function(){
        // 获取服务器响应数据
        console.log(xhr.responseText)
      }

你可能感兴趣的:(ajax)