码迷,mamicode.com
首页 > Web开发 > 详细

AJAX---发送POST请求

时间:2020-02-06 23:30:12      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:charset   div   元素   cli   根据   http   state   hang   amp   

发送POST请求

 

POST 请求过程中,都是采用请求体承载需要提交的数据

 var xhr = new XMLHttpRequest()

 

    // open 方法的第一个参数的作用就是设置请求的 method
    xhr.open(‘POST‘, ‘./add.php‘)

 

    // 设置请求头中的 Content‐Type 为 application/x‐www‐form‐urlencoded
    // 标识此次请求的请求体格式为 urlencoded 以便于服务端接收数据
    xhr.setRequestHeader(‘Content‐Type‘, ‘application/x‐www‐form‐urlencoded‘)

 

    // 需要提交到服务端的数据可以通过 send 方法的参数传递
    // 格式:key1=value1&key2=value2
    xhr.send(‘key1=value1&key2=value2‘)

 

xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        console.log(this.responseText)
      }
    }

 

练习代码

<!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>

 

AJAX---发送POST请求

标签:charset   div   元素   cli   根据   http   state   hang   amp   

原文地址:https://www.cnblogs.com/jane-panyiyun/p/12271076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!