案例--登录(简易版)

逻辑:

1. 我得在点击登录按钮的时候发送请求

  => 需要给 form 标签绑定一个 submit 事件

  => 注意: 在 事件内, 需要阻止默认行为

2. 获取到用户输入的内容

3. 表单验证

  => 非空验证

  => 正则验证

4. 把用户名和密码发送给后端

  => 使用 ajax 发送

  => 请求地址和方式, 看接口文档

5. 根据后端给出的响应, 来做对应的操作

const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')

// 1. 绑定事件
form.addEventListener('submit', e => {
  // 处理事件对象兼容
  e = e || window.event
  // 阻止默认行为
  try { e.preventDefault() } catch(err) { e.returnValue = false }

  // 2. 获取到用户输入的内容
  const name = nameInp.value
  const pwd = pwdInp.value

  // 3. 非空验证
  if (!name || !pwd) return alert('请完整填写表单')

  // 4. 发送 ajax 请求
  const xhr = new XMLHttpRequest()
  xhr.open('POST', 'http://localhost:8888/users/login')
  xhr.onload = function () {
    const res = JSON.parse(xhr.responseText)
    console.log(res);

    if (res.code === 0) {
      alert(res.message)
      return
    }

    // 跳转页面
    window.location.href = 'https://www.jd.com'
  }
  // 因为是 post 请求, 并且携带了参数, 需要提前设置请求头
  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  xhr.send(`username=${ name }&password=${ pwd }`)
})

<form>
  <label>
    用户名: <input class="username" type="text">
  </label>
  <br>
  <label>
    密码: <input class="password" type="text">
  </label>
  <button>登录</button>
</form>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值