Json的知识点与练习

Json的知识点与练习

Json对象


```typescript
<script>
    let json = {
      // 键值对   key:value
      'id': '001',
      'name': '张三',
      'age': 18
    }

    // 数组对象
    let stus =
      [
        { 'id': '001', 'name': '张三', 'age': 18 },
        { 'id': '002', 'name': '张无', 'age': 17 },
        { 'id': '003', 'name': '张流', 'age': 16 }
      ]
    // 访问
      document.write('<h2>'+stus[1].name+'</h2>')

  </script>

知识点与练习的结合

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>验证码</title>
  <style>
    img {
      width: 100px;
      height: 50px;
    }
  </style>
</head>

<body>
  <form action="#">
    <input type="text" name="yzm" placeholder="验证码">
    <img src="img/验证码.png" alt="">
    <input type="submit" value="提交" class="sb">
  </form>
  <script>
    let ya = ''//验证码
    document.querySelector('img').onclick = function () {
      // 创建对象
      let xmlReq;
      // 检查浏览器是否支持XMLHttpRequest
      if (window.XMLHttpRequest) {
        xmlReq = new XMLHttpRequest()
      } else {
        xmlReq = new ActiveXObject()//老版本的ie使用
      }
      // 发送请求
      xmlReq.open('GET',//提交方式
        // url
        'https://route.showapi.com/26-4?appKey=2A84e7dbacEf4797A5A2637bFcB05882',
        true)
      xmlReq.send()

      // 获取响应
      xmlReq.onreadystatechange = function () {
        // 响应成功
        if (xmlReq.readyState == 4 && xmlReq.status == 200) {
          // xmlhttp.responseText响应的数据   字符串格式
          // alert(xmlReq.responseText)
          let str = xmlReq.responseText
          // 把字符串转换成json对象
          let json = JSON.parse(str)
          // alert(json)
          // alert(json.showapi_res_body.img_path_https)
          document.querySelector('img').setAttribute('src', json.showapi_res_body.img_path_https)
          ya = json.showapi_res_body.text
        } else {
          console.log('xmlReq.status' + xmlReq.status);
          console.log('xmlReq.readyState' + xmlReq.readyState);

        }
      }
    }

    // 验证
    document.querySelector('.sb').onclick = function () {
      let val = document.getElementsByName('yzm')[0].value
      if (val === ya) {
        alert('提交成功')
      } else {
        alert('提交失败')
      }
    }

  </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值