Skip to content

Ajax

1.URL组成

URL:统一资源定位符

1.1协议http

http协议::超文本传入协议,规定浏览器和服务器之间传输数据的格式

1.2域名

域名:: 由一组点分隔的字符串,用于标记服务器在互联网的位置,如www.baidu.com

1.3资源路径

资源路径:: 由一组斜杠分隔的字符串,如/a/b/c.html,标记资源在服务器下的具体位置

2.URL参数

定义:浏览器提供给服务器的额外信息,让服务器返回浏览器想要的数据 语法:http://www.xxx.com?param1=xxx&param2=yyy

2.axois

2.1查询参数

语法:使用axois提供的params选项

WARNING

axios在允许的时候把参数名和值,回拼接到url?参数名=值

js
axios({
  url: 'http://hmajax.itheima.net/api/city',
  params: {
    pname: '河北省'
  }
}).then(result => {
  // 对服务器返回的数据做后续处理
})
axios({
  url: 'http://hmajax.itheima.net/api/city',
  params: {
    pname: '河北省'
  }
}).then(result => {
  // 对服务器返回的数据做后续处理
})

案例:

html
<!DOCTYPE html>
<html lang="zh_CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04.案例_地区查询</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
  <style>
    :root {font-size: 15px;}
    body {padding-top: 15px;}
  </style>
</head>
<body>
  <div class="container">
    <form id="editForm" class="row">
      <!-- 输入省份名字 -->
      <div class="mb-3 col">
        <label class="form-label">省份名字</label>
        <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
      </div>
      <!-- 输入城市名字 -->
      <div class="mb-3 col">
        <label class="form-label">城市名字</label>
        <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
      </div>
    </form>
    <button type="button" class="btn btn-primary sel-btn">查询</button>
    <br><br>
    <p>地区列表: </p>
    <ul class="list-group">
      <!-- 示例地区 -->
      <li class="list-group-item">东城区</li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    /*
      获取地区列表: http://hmajax.itheima.net/api/area
      查询参数:
        pname: 省份或直辖市名字
        cname: 城市名字
    */
    //获取class类名
    document.querySelector('.sel-btn').addEventListener('click', () => {
      //获取省份和城市的名字
      let province = document.querySelector('.province').value;
      let city = document.querySelector('.city').value;
      // 发起请求
      axios({
        url: 'http://hmajax.itheima.net/api/area',
        params: {
          pname: province,
          cname: city
        }
      }).then(result => {
        const resultlist = result.data.list.map(function(ele){
          return `<li class="list-group-item">${ele}</li>`
        }).join('')
        document.querySelector('.list-group-item').innerHTML = resultlist;
      })
    })
  </script>
</body>

</html>
<!DOCTYPE html>
<html lang="zh_CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04.案例_地区查询</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
  <style>
    :root {font-size: 15px;}
    body {padding-top: 15px;}
  </style>
</head>
<body>
  <div class="container">
    <form id="editForm" class="row">
      <!-- 输入省份名字 -->
      <div class="mb-3 col">
        <label class="form-label">省份名字</label>
        <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
      </div>
      <!-- 输入城市名字 -->
      <div class="mb-3 col">
        <label class="form-label">城市名字</label>
        <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
      </div>
    </form>
    <button type="button" class="btn btn-primary sel-btn">查询</button>
    <br><br>
    <p>地区列表: </p>
    <ul class="list-group">
      <!-- 示例地区 -->
      <li class="list-group-item">东城区</li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    /*
      获取地区列表: http://hmajax.itheima.net/api/area
      查询参数:
        pname: 省份或直辖市名字
        cname: 城市名字
    */
    //获取class类名
    document.querySelector('.sel-btn').addEventListener('click', () => {
      //获取省份和城市的名字
      let province = document.querySelector('.province').value;
      let city = document.querySelector('.city').value;
      // 发起请求
      axios({
        url: 'http://hmajax.itheima.net/api/area',
        params: {
          pname: province,
          cname: city
        }
      }).then(result => {
        const resultlist = result.data.list.map(function(ele){
          return `<li class="list-group-item">${ele}</li>`
        }).join('')
        document.querySelector('.list-group-item').innerHTML = resultlist;
      })
    })
  </script>
</body>

</html>

2.2常用请求方法

请求方法操作
GET向服务器请求数据
POST向服务器提交数据
PUT向服务器修改数据(全部)
DELETE向服务器删除数据
PATCH向服务器修改数据(部分)

封装简易axios

js
//封装简易axios
function Myaxois(config) {
  return new Promise((reslove, reject) => {
    //新建一个xmlhttprequest对象
    const xhr = new XMLHttpRequest()
    //判断是否有params对象
    if (config.params) {
      //创建URLsearchParams
      const urlparams = new URLSearchParams(config.params)
      const queryString = urlparams.toString()
      //将获取到的字符串拼接到url后面
      config.url += `?${queryString}`
    }
    //发起请求,
    xhr.open(config.method || 'GET', config.url)
    //未xhr添加事件监听:
    xhr.addEventListener('loadend', function () {
      //查看是否调用成功
      if (xhr.status >= 200 && xhr.status < 300) {
        reslove(JSON.parse(xhr.response))
      } else {
        reject(new Error('请求失败'))
      }
    })
    //判断有没有data
    if(config.data){
      //转成一个json对象
      const jsonStr = JSON.stringify(config.data)
      //指定请求数据的类型
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(jsonStr)
    }else{
      xhr.send()
    }
  })
}
Myaxois({
  url: 'http://hmajax.itheima.net/api/area',
  params: {
    pname: '辽宁省',
    cname: '大连市'
  }
}).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})
//封装简易axios
function Myaxois(config) {
  return new Promise((reslove, reject) => {
    //新建一个xmlhttprequest对象
    const xhr = new XMLHttpRequest()
    //判断是否有params对象
    if (config.params) {
      //创建URLsearchParams
      const urlparams = new URLSearchParams(config.params)
      const queryString = urlparams.toString()
      //将获取到的字符串拼接到url后面
      config.url += `?${queryString}`
    }
    //发起请求,
    xhr.open(config.method || 'GET', config.url)
    //未xhr添加事件监听:
    xhr.addEventListener('loadend', function () {
      //查看是否调用成功
      if (xhr.status >= 200 && xhr.status < 300) {
        reslove(JSON.parse(xhr.response))
      } else {
        reject(new Error('请求失败'))
      }
    })
    //判断有没有data
    if(config.data){
      //转成一个json对象
      const jsonStr = JSON.stringify(config.data)
      //指定请求数据的类型
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(jsonStr)
    }else{
      xhr.send()
    }
  })
}
Myaxois({
  url: 'http://hmajax.itheima.net/api/area',
  params: {
    pname: '辽宁省',
    cname: '大连市'
  }
}).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})