Ajax (1)

news2024/9/30 11:27:07

什么是Ajax:

浏览器与服务器进行数据通讯的技术,动态数据交互

axios库地址:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

如何使用呢? 我们现有个感性的认识

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    axios({
      url: 'http://hmajax.itheima.net/api/province'
    }).then(result => {
      console.log(result)
      console.log(result.data.list)
    })
  </script>

获取如下:

展示到页面:

<body>
  <p></p>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    axios({
      url: 'http://hmajax.itheima.net/api/province'
    }).then(result => {
      const p=document.querySelector('p')
      p.innerHTML=result.data.list.join('<br>')
    })
  </script>
</body>

认识URL

URL是统一资源定位符,俗称网址,访问网络资源

组成: 协议、域名、资源路径

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

域名:标记服务器在互联网中的方位

资源路径:标记资源在服务器下具体位置

URL查询参数

浏览器提供给服务器的额外信息,让服务器返回浏览器想要的数据

语法:

http://xxx.com/xxx/xxx?参数名1=值1&参数名2=值2

axios-查询参数

语法: 使用axios提供的params选项(拿数据时的查询参数)

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    axios({
      url: 'http://hmajax.itheima.net/api/city',
      params: {
        pname: '河北省'
      }
    }).then(result => {
      console.log(result)
    })
  </script>

axios原码在运行时把参数名自动拼接到url上

地区查询:

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

<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, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

  <title>~</title>

  <link rel="shortcut icon" href="https://www.bilibili.com/favicon.ico">
  <link rel="stylesheet" href="css/初始化表.css">
  <link rel="stylesheet" href="bootstrap\css\bootstrap.min.css">
  <meta name="keywords" content="..." />

  <style>
    /*写代码时始终要考虑权重问题!*/
    @font-face {
      font-family: 'icomoon';
      src: url('fonts/icomoon.eot?au9n7q');
      src: url('fonts/icomoon.eot?au9n7q#iefix') format('embedded-opentype'),
        url('fonts/icomoon.ttf?au9n7q') format('truetype'),
        url('fonts/icomoon.woff?au9n7q') format('woff'),
        url('fonts/icomoon.svg?au9n7q#icomoon') format('svg');
      font-weight: normal;
      font-style: normal;
      font-display: block;
    }

    .center-block {
      display: block;
      margin-left: auto;
      margin-right: auto;
      width: 500px;
    }
  </style>
</head>

<body>
  <div class="center-block">
    <form class="form-horizontal">
      <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">Province</label>
        <div class="col-sm-10">
          <input type="text" class="form-control input1" id="inputEmail3" placeholder="Province">
        </div>
      </div>
      <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">City</label>
        <div class="col-sm-10">
          <input type="text" class="form-control input2" id="inputPassword3" placeholder="City">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button class="btn btn-default" type="button">查询</button>
        </div>
      </div>
    </form>
    <p>地区列表:</p>
    <ul class="list-group">
    </ul>
    </table>
  </div>



  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    const input1 = document.querySelector('.input1')
    const input2 = document.querySelector('.input2')
    const btn = document.querySelector('.btn')

    btn.addEventListener('click', () => {
      let pname = input1.value
      let cname = input2.value
      axios({
        url: 'http://hmajax.itheima.net/api/area',
        params: {
          pname: pname,
          cname: cname
        }
      }).then(result => {
        let list = result.data.list
        let str = list.map(item => `<li class="list-group-item">${item}</li>`
        ).join('')
        console.log(str)
        document.querySelector('.list-group').innerHTML = str
      })
    })

  </script>
</body>

</html>

常用请求方法

资源的操作:

get:get请求可以得到我们想要的具体的数据,then方法指定成功时候的回调(params)

post:操作post请求增加一条或者多条数据,可以采用JSON的形式传输数据

put:我们采put请求修改数据,可以具体修改某一条数据

delete:删除数据

method:请求方法,get可以省略

data:提交数据

<script>
    
      axios({
        url: 'http://hmajax.itheima.net/api/register',
        method:'post',
        data: {
          username: 'qwertyu123',
          password: '123456'
        }
      }).then(result => {
        console.log(result)
      })

  </script>

axios错误处理

语法:

在then后通过(点)语法调用catch方法,传入回调函数并定义形参

<script>
    
      axios({
        url: 'http://hmajax.itheima.net/api/register',
        method:'post',
        data: {
          username: 'qwertyu123',
          password: '123456'
        }
      }).then(result => {
        console.log(result)
      }).catch(error=>{
        alert(error.response.data.message)
      })
  </script>

浏览器是如何把内容发送给服务器的?

这与请求报文有关

HTTP协议-请求报文

http格式规定了浏览器发送及浏览器返回内容的格式

请求报文:浏览器按照http协议要求的格式,发送给服务器的内容

请求报文的组成:

请求行:请求方法(如post),URL,协议

请求头:以键值对的格式携带的附加信息,如:Content-Type

空格:分隔请求头,空行之后是发送给服务器的资源

请求体:发送到资源

在浏览器中可以看到这些内容

响应报文

响应报文:服务器按照http协议要求的格式,返回给浏览器的内容

响应报文的组成:

响应行(状态行):协议,http响应状态码,状态信息

响应头:以键值对的格式携带的附加信息,如:Content-Type

空格:分隔响应头,空行之后是服务器返回的资源

响应体:返回的资源

http响应状态码

用来表明请求是否成功完成

2xx :请求成功

4xx:客户端错误

404:服务器找不到资源

接口

在使用AJAX与后端通讯,使用的URL,请求方法,以及参数

登录界面案例:

 <style>
    /*写代码时始终要考虑权重问题!*/
    @font-face {
      font-family: 'icomoon';
      src: url('fonts/icomoon.eot?au9n7q');
      src: url('fonts/icomoon.eot?au9n7q#iefix') format('embedded-opentype'),
        url('fonts/icomoon.ttf?au9n7q') format('truetype'),
        url('fonts/icomoon.woff?au9n7q') format('woff'),
        url('fonts/icomoon.svg?au9n7q#icomoon') format('svg');
      font-weight: normal;
      font-style: normal;
      font-display: block;
    }

    .form-control {
      width: 400px;
    }

    .btn-block {
      width: 100px;
    }

    .alert {
      width: 400px;
      height: 50px;
      opacity: 0;
    }
  </style>
</head>

<body>
  <div class="container">

    <form class="form-signin">
      <h2 class="form-signin-heading">Please sign in</h2>
      <div class="alert " role="alert">...</div>
      <label for="input" class="sr-only">Username</label>
      <input type="text" id="input" class="form-control username" placeholder="Username" required autofocus>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="inputPassword" class="form-control password" placeholder="Password" required>
      <div class="checkbox">
        <label>
          <input type="checkbox" value="remember-me"> Remember me
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
    </form>

  </div>


  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>

    const btn = document.querySelector('.btn')
    const username = document.querySelector('.username')
    const password = document.querySelector('.password')
    const Alert = document.querySelector('.alert')

    function MyAlert() {
      Alert.style.opacity = 1
      if (username.value.length < 8 || password.value.length < 6) {
        Alert.classList.remove('alert-success')
        Alert.classList.add('alert-danger')
        Alert.innerHTML = '错误!'

      }
      else {
        Alert.classList.remove('alert-danger')
        Alert.classList.add('alert-success')

        Alert.innerHTML = '登录成功'
      }
      return false
    }


    btn.addEventListener('click', function () {
      let flag = MyAlert()
      setTimeout(() => {
        Alert.style.opacity = 0
      }, 2000)
      if (!flag)
      {
        return
      }
        axios({
          url: 'http://hmajax.itheima.net/api/login',
          method: 'post',
          data: {
            username: username.value,
            password: password.value
          }
        }).then(result => {
          console.log(result)
        }).catch(error => {
        })
    })

  </script>

</body>

form-serialize.js

可以快速获取表单元素,通过解构对象获得用户信息

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1506029.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Python-Docx库】Word与Python的完美结合

今天给大家分享Python处理Word的第三方库&#xff1a;Python-Docx。 什么是Python-Docx&#xff1f; Python-Docx是用于创建和更新Microsoft Word&#xff08;.docx&#xff09;文件的Python库。 日常需要经常处理Word文档&#xff0c;用Python的免费第三方包&#xff1a;Pyt…

【自制操作系统】系统启动流程,工具使用和启动区的制作

&#x1f4dd;本文介绍 本文主要从系统系统的启动流程开始&#xff0c;中间介绍一些所用工具的使用方法&#xff0c;最后将完成一个启动区的制作。此次的启动区只涉及到汇编代码。 &#x1f44b;作者简介&#xff1a;一个正在积极探索的本科生 &#x1f4f1;联系方式&#xff1…

《MySQL实战45讲》课程大纲

1MySQL实战45讲-01基础架构&#xff1a;一条SQL查询语句是如何执行的&#xff1f;2MySQL实战45讲-02日志系统&#xff1a;一条SQL更新语句是如何执行的&#xff1f;3MySQL实战45讲-03事务隔离&#xff1a;为什么你改了我还看不见&#xff1f;4MySQL实战45讲-04深入浅出索引&…

vue3 ref获取子组件显示 __v_skip : true 获取不到组件的方法 怎么回事怎么解决

看代码 问题出现了 当我想要获取这个组件上的方法时 为什么获取不到这个组件上的方法呢 原來&#xff1a; __v_skip: true 是 Vue 3 中的一个特殊属性&#xff0c;用于跳过某些组件的渲染。当一个组件被标记为 __v_skip: true 时&#xff0c;Vue 将不会对该组件进行渲染&am…

Springboot——JSR303校验

1. 请求参数的合法性校验 使用基于JSR303的校验框架实现&#xff0c;Springboot提供了JSR-303的支持&#xff0c;它就是spring-boot-starter-validation&#xff0c;他包括了很多的校验规则&#xff0c;只需要在模型中通过注解指定校验规则&#xff0c;在Controller方法上开启校…

map和set(二)——AVL树的简单实现

引入 二叉搜索树有其自身的缺陷&#xff0c;假如往树中 插入的元素有序或者接近有序&#xff0c;二叉搜索树就会退化成单支树&#xff0c;时间复杂度会退化成O(N)&#xff0c;因此 map、set等关联式容器的底层结构是对二叉树进行了平衡处理&#xff0c;即采用平衡树来实现。简…

深入了解二叉搜索树:原理、实现与应用

目录 一、介绍二叉搜索树 二、二叉搜索树的基本性质 三、二叉搜索树的实现 四、总结 在计算机科学中&#xff0c;数据结构是构建算法和程序的基础。其中&#xff0c;二叉搜索树&#xff08;Binary Search Tree&#xff0c;简称 BST&#xff09;作为一种常见的数据结构&#…

从新手到高手:一站式 SQL Server 学习平台!

介绍&#xff1a;SQL Server是由微软公司开发的关系数据库管理系统&#xff08;RDBMS&#xff09;&#xff0c;自1989年推出以来&#xff0c;已成为全球主流的数据库之一。以下是对SQL Server的详细介绍&#xff1a; 易用性与可伸缩性&#xff1a;SQL Server以其易用性和良好的…

题目:泡澡(蓝桥OJ 3898)

问题描述&#xff1a; 解题思路&#xff1a; 图解&#xff1a;&#xff08;以题目样例为例子&#xff09; 注意点&#xff1a;题目的W是每分钟最大出水量&#xff0c;因此有一分钟的用水量大于出水量则不通过。 补充&#xff1a;差分一般用于对一段区间每个元素加相同值&#x…

arp 代理配置示例

一、应用场景&#xff1a; 当 R1 和 R3 配置静态路由下一跳为接口的时候&#xff0c;让 R2 充当 arp 代理&#xff0c;允许 R1、R3 互访 二、拓朴如下&#xff1a; 三、配置代码&#xff1a; [R1] ip route-static 10.1.23.0 255.255.255.0 GigabitEthernet0/0/0[R2] interf…

Git学习笔记(流程图+示例)

概念 图中左侧为工作区&#xff0c;右侧为版本库。Git 的版本库里存了很多东西&#xff0c;其中最重要的就是暂存区。 • 在创建 Git 版本库时&#xff0c;Git 会为我们自动创建一个唯一的 master 分支&#xff0c;以及指向 master 的一个指 针叫 HEAD。&#xff08;分支和HEAD…

服务器又被挖矿记录

写在前面 23年11月的时候我写过一篇记录服务器被挖矿的情况&#xff0c;点我查看。当时是在桌面看到了bash进程CPU占用异常发现了服务器被挖矿。 而过了几个月没想到又被攻击&#xff0c;这次比上次攻击手段要更高明点&#xff0c;在这记录下吧。 发现过程 服务器用的是4090…

【数据结构】详解时间复杂度和空间复杂度的计算

一、时间复杂度&#xff08;执行的次数&#xff09; 1.1时间复杂度的概念 1.2时间复杂度的表示方法 1.3算法复杂度的几种情况 1.4简单时间复杂度的计算 例一 例二 例三 1.5复杂时间复杂度的计算 例一&#xff1a;未优化冒泡排序时间复杂度 例二&#xff1a;经过优化…

Go语言必知必会100问题-19 浮点数溢出问题

问题呈现 在Go语言中&#xff0c;有两种浮点数类型&#xff08;虚数除外&#xff09;&#xff1a;float32和float64. 浮点数是用来解决整数不能表示小数的问题。我们需要知道浮点数算术运算是实数算术运算的近似&#xff0c;下面通过例子说明浮点数运算采用近似值的影响以及如…

LeetCode:143.重排链表

143. 重排链表 解题过程 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(int val, ListNode next) { this.val val; this.next next; …

python 蓝桥杯之并查集

文章目录 总述合并过程查找过程算法实战实战1 总述 并查集&#xff08;Disjoint-set Union&#xff0c;简称并查集&#xff09;是一种用来管理元素分组情况的数据结构。它主要用于解决集合的合并与查询问题&#xff0c;通常涉及到以下两种操作&#xff1a; 合并&#xff08;Uni…

Redis基础篇:初识Redis(认识NoSQL,单机安装Redis,配置Redis自启动,Redis客户端的基本使用)

目录 1.认识NoSQL2.认识Redis3.安装Redis1.单机安装Redis2.配置redis后台启动3.设置redis开机自启 4.Redis客户端1.Redis命令行客户端2.图形化桌面客户端 1.认识NoSQL NoSQL&#xff08;Not Only SQL&#xff09;数据库是一种非关系型数据库&#xff0c;它不使用传统的关系型数…

Android14 Handle机制

Handle是进程内部, 线程之间的通信机制. handle主要接受子线程发送的数据, 并用此数据配合主线程更新UI handle可以分发Message对象和Runnable对象到主线程中, 每个handle实例, 都会绑定到创建他的线程中, 它有两个作用,: (1) 安排消息在某个主线程中某个地方执行 (2) 安排…

解放生产力,AI加持你也能做这些事!

去年网上流行一个说法叫一人企业或超级IP。一个人就是一家公司&#xff0c;可以更加专注于自身核心技能。既能对工作拥有更大的自主性和控制力&#xff0c;又能舍弃了传统公司管理等繁琐的事务工作&#xff0c;可以全面释放自己的兴趣和潜力。 这个概念给笔者留下了比较深的印…

开源的python 游戏开发库介绍

本文将为您详细讲解开源的 Python 游戏开发库&#xff0c;以及它们的特点、区别和应用场景。Python 社区提供了多种游戏开发库&#xff0c;这些库可以帮助您在 Python 应用程序中实现游戏逻辑、图形渲染、声音处理等功能。 1. Pygame 特点 - 基于 Python 的游戏开发库。…