当前位置: 首页 > news >正文

AJAX(4)——XMLHttpRequest

XMLHttpRequest

定义:XMLHttpRequest(XHR)对象用于与服务器交互。通过XMLHttpRequest可以在不刷新页面的情况下请求特定URL,获取数据。这允许网页在不影响用于操作的情况下,更新页面的局部内容。XMLHttpRequest在AJAX编程中被大量使用

关系:axios内部采用XMLHttpRequest与服务器交互


使用XMLHttpRequest

步骤:

  1. 创建XMLHttpRequest对象
  2. 配置请求方法和请求URL地址
  3. 监听loadend事件,接收响应结果
  4. 发起请求
<body><script>const xhr = new XMLHttpRequest()//配置请求地址xhr.open('GET', 'http://hmajax.itheima.net/api/province')//监听loadend,接收响应结果xhr.addEventListener('loadend', () => {console.log(xhr.response);   获取响应数据const data = JSON.parse(xhr.response)    //转换为对象console.log(data.list);})//发起请求xhr.send()</script>

查询参数 

语法:

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

    const xhr = new XMLHttpRequest()xhr.open('GET', 'http://hmajax.itheima.net/api/city?pname=辽宁省')xhr.addEventListener('loadend', () => {console.log(xhr.response);})xhr.send()

 

 XMLHttpRequest数据提交

请求头设置Content-Type:application/json

请求体携带JSON

 

    //XHR数据提交document.querySelector('.btn').addEventListener('click', () => {const xhr = new XMLHttpRequest()xhr.open('POST', 'http://hmajax.itheima.net/api/register')xhr.addEventListener('loadend', () => {console.log(xhr.response);})//设置请求头xhr.setRequestHeader('Content-Type', 'application/json')const obj = {username: 'itheima908',password: '765421'}const str = JSON.stringify(obj)//设置请求体,发送请求xhr.send(str)})

 


http://www.mrgr.cn/news/12219.html

相关文章:

  • C语言程序设计-联系篇
  • Mybatis框架基础
  • OpenCV入门12.2:SURF与SIFT比较及SURF示例
  • 如何在没有屏幕时间密码或 Apple ID 的情况下重置 iPhone
  • 【Tomcat】Tomcat10部署war包无法启动
  • 鸿蒙(API 12 Beta3版)【使用AVScreenCapture录屏取原始码流(C/C++)】视频播放与录制
  • 手写题之链式调用
  • 全方位解析红鲸音视频会议SDK助力系统功能集成
  • 作业0827
  • 搭建ELK-Filebeat采集系统日志
  • 使用SparkGraphX进行图计算时的编码问题
  • 如何完美实现 Go 服务的平滑升级
  • 8. 为什么 Java 中 HashMap 的默认负载因子是 0.75?
  • Unity 离线文档快速访问处理文件
  • 高效能低延迟:EasyCVR平台WebRTC支持H.265在远程监控中的优势
  • Java-List分批多线程执行
  • ModBus RTU、ModBus ASCII、ModBus TCP,它们有什么区别?
  • 算法训练营|图论第二天 99.岛屿数量 100.岛屿的最大面积
  • 【北森-注册安全分析报告-无验证方式导致安全隐患】
  • 列式存储数据库(Columnar Database)