首页 > 其他分享 >js原生ajax发起的请求xhr

js原生ajax发起的请求xhr

时间:2022-10-08 20:57:19浏览次数:35  
标签:console log JSON js xhr ajax var open

使用xhr发起GET请求步骤:


发起一个GET请求例子:

//1、创建一个xhr对象
var xhr = new XMLHttpRequest();
//2、调用xhr.open()函数 请求方式 获取地址
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks');
//3、调用 send 函数,发起 Ajax 请求
xhr.send();
//4、监听onreadystatechang事件
xhr.onreadystatechange = function() {
// 4.1 监听 xhr 对象的请求状态 readyState ;与服务器响应的状态 status
if (xhr.readyState === 4 && xhr.status === 200) {
    // 4.2 打印服务器响应回来的数据
    console.log(xhr.responseText)
}

}

了解readyState状态码:

带参数的Get请求 查询字符串

URL编码与URL解码

例子:

var str = '黑马程序员'
//编码函数使用encodeURI
var str2 = encodeURI(str)
console.log(str2)

console.log('----------')
//解码函数使用decodeURI
var str3 = decodeURI('%E9%BB%91%E9%A9%AC')
console.log(str3)

发起一个post请求:

//1、创建一个xhr对象
var xhr = new XMLHttpRequest();
//2、调用xhr.open函数 url地址 和请求方式
xhr.open('Post','http://www.liulongbin.top:3006/api/addbook');
//3、发起一个请求头 cont-type 固定写法(xhr.setRequestHeader) 必须写
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//4、调用send()发送数据

xhr.send('bookname=江南&author=林俊杰&publisher=新加坡');
//5、监听事件
xhr.onreadystatechange=function(){
  //判断请求状态和响应
  if(xhr.readyState === 4 && xhr.status === 200){
    console.log(xhr.responseText)
  }
}

什么是JSON:

使用场景例子:

var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText)  //输出字符串数据
    console.log(typeof xhr.responseText) //输出类型(String)
	
	//从json字符串转化为js对象使用: JSON.parse()对象
	// 从js对象中转化为json对象使用: JSON.Stringify()对象
    //使用JSON.parse()函数把字符串转化为js对象
    var result = JSON.parse(xhr.responseText)
    console.log(result)
  }
}

JSON : 使用时候需要注意的地方

封装自己的ajax函数:

1、需要把 data 对象,转化成查询字符串的格式,从而提交给服务器,因此提前定义 resolveData 函数:

2、 在 itheima() 函数中,创建 xhr 对象 并监听 onreadystatechange 事件:接受用户传来的一个option值 定义一个option参数选项值

XMLHTTPRequest 新特性


1、设置请求时限:

var xhr = new XMLHttpRequest()
// 设置 超时时间.timeout 3秒
xhr.timeout=300;

// 设置超时以后的处理函数ontimeout
//如果超时则回调函数 ontimeout属性发送请求

xhr.ontimeout=function(re){
  return alert("请求超时")
}
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText))
  }
}

** 2、可以使用FormData表单存储表单对象:**

// 1. 创建 FormData 实例
var fd = new FormData()
// 2. 调用 append 函数,向 fd 中追加数据
fd.append('age','123')
fd.append('uname', 'zs')
fd.append('upwd', '123456')

var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
//接受FormData的数据fd
xhr.send(fd)

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    //JSON.parse 字符转化为对象 相仿则JSON.Stringify
    console.log(JSON.parse(xhr.responseText))
  }
}

** 3、应用场景:使用FromData 快速获取表单数据: **

//1、获取表单元素
var str = document.getElementById('form1');
//2、监听表单的submit事件
str.addEventListener('submit',function(e){
  //阻止表单默认提交
  e.preventDefault();

  //创建formdata表单获取表单元素
  var obj = new FormData(str);
  //创建xhr对象
  var xhr =new XMLHttpRequest();
  //调用.open()
  xhr.open('POST','http://www.liulongbin.top:3006/api/formdata');
  xhr.send(obj);
  //监听ajax事件
  xhr.onreadystatechange=function(){
    if(xhr.readyState === 4  &&  xhr.status === 200){
      //转化为js对象
      console.log(JSON.parse(xhr.responseText))
    }
  }
  
})

标签:console,log,JSON,js,xhr,ajax,var,open
From: https://www.cnblogs.com/yxn001/p/16769954.html

相关文章

  • #yyds干货盘点#慎用JSON.stringfy
    项目中遇到一个bug,一个组件为了保留一份JSON对象,使用JSON.stringify将其转换成字符串,这样做当然是为了避免对象是引用类型造成数据源的污染。但发现后面使用JSON.pars......
  • js 日期格式化
    用法://2022-10-0622:01:09formatDate("yyyy-MM-ddhh:mm:ss",newDate());//2022-10-0622:01:09dateFormat("yyyy-MM-ddhh:mm:ss",newDate(1665064915000));......
  • JSON语法格式
    javascript作用:改变HTML内容JavaScript内嵌于HTML网页中,通过浏览器内置的JavaScript引擎进行解释执行,把一个原本只用来显示的页面转变成支持用户交互的页面程序。Javascr......
  • js字符串
    字符串声明1.直接声明 varstr='hello'2.使用new关键字(会开辟新的内存空间)varstr=newString('hello')newString和String的区别 前者开辟空间后者只是进行......
  • video.js使用总结
    video.js使用总结video.js是通过HTML5将原生的video标签进行渲染的js开源工具。拥有更多的API,进行个性化定制。在vue项目中引入video.jspackage.json:"dependencies":......
  • vue.js3:用el-loading显示加载动画([email protected] / [email protected])
    一,el-loading1,文档地址:https://element-plus.gitee.io/zh-CN/component/loading.html2, 查看element-plus的版本:liuhongdi@lhdpc:/data/vue/imgtouch$npmlist......
  • net中c#教程 Json字符串的常用操作
    json字符串格式的出现,大大地方便了不同系统间的数据传输,无论是Net项目还是Java项目都适用。今天就分享几个json的常用操作。我们是基于Newtonsoft.Json这个第三方类库实现......
  • Collecting package metadata (current_repodata.json): failed--2个解决方案
    问题描述:在​​cmd.exe​​​中新建​​Python​​​环境,报错​​Collectingpackagemetadata(current_repodata.json):failed​​报错界面寻找问题所在重装过anaconda,在......
  • js检测数据类型得四种方式
    1.typeof:返回一个字符串,表示操作数的类型。  语法:typeof(变量)//ortypeof变量示例:  console.log(typeof2)//number  console.log(type......
  • 企业微信第三方开发JSApi调用previewFile没反应 无报错
    在开发企业微信第三方应用时,使用JSApi。初始化wx.config时没有报错,并在jsApiList里加上了previewFile。经过测试,发现IPhone端wx.previewFile为undefined。当前调用方式:......