js原生ajax发起的请求xhr
使用Xhr发起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))
}
}
})
#### 4、上传文件:
#### 上传文件实例:
点击查看代码
//1、获取上传按钮
var btnsc =document.querySelector('#btnfile');
//2、给上传按钮绑定一个监听事件
btnsc.addEventListener('click',function(){
// console.log("hello world ");
//3、获取上传的文件数组
var files = document.querySelector('#files').files;
//4、获取文件后判断是否为空
if(files.length<=0){
return alert('请上传文件')
}
console.log('上传完成')
// 向 FormData 中追加文件
//5、创建一个formDate对象 存储上传的文件数据
var from = new FormData();
//6、追加数据到formdata中 这里avatar(后台)是头像属性
from.append('avatar',files[0]);
//7、发起一个post请求
var xhr =new XMLHttpRequest();
//8、计算文件的上传速度
//监听 监听 xhr.upload 的 onprogress 事件
xhr.upload.onprogress=function(e){
// e.lengthComputable 是一个布尔值,表示当前上传的资源是否具有可计算的长度
//判断布尔是否为true 是则执行
if(e.lengthComputable){
// e.loaded 已传输的字节
// e.total 需传输的总字节
// 上传字节等于 已传输 除以 需总字节
//1、计算当前的上传进度
var percentComplete = Math.ceil((e.loaded/e.total)*100)
// console.log(lct);
//通过jquery 获取对应进度条的id
//.attr()获取当前的宽度 .html()显示当前的进度
$('#percent').attr('style','width:' + percentComplete + '%').html(percentComplete + '&')
}
}
xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar');
xhr.send(from);
//监听事件
xhr.onreadystatechange=function(){
if(xhr.readyState === 4 && xhr.status === 200){
// console.log(xhr.responseText);
var data = JSON.parse(xhr.responseText);
// 判断data的status是否等于两百 渲染数据
if(data.status === 200){
//成功则渲染数据到img标签
document.querySelector('#imgs').src='http://www.liulongbin.top:3006' + data.url
}else{
console.log('上传文件失败')
}
}
}
})
### Jquery实现上传:
点击查看代码
<input type="file" id="file1" />
<button id="btnUpload">上传文件</button>
<br />
<img src="./loading.gif" alt="" style="display: none;" id="loading" />
<img src="" id="imgss" >
<script>
$(function () {
//实现loading效果 注意: $(document).ajaxStart() 函数会监听当前文档内所有的 Ajax 请求。
//Ajax 请求开始时,执行 ajaxStart 函数。
//在 ajaxStart 的 callback 中显示 loading 效果,示例代码如下:
$(document).ajaxStart(function(){
$('#loading').show();
})
//成功之后需要把loading效果隐藏
//可以使用.ajaxstop
$(document).ajaxStop(function(){
$('#loading').hide()
})
//1、给按钮绑定一个事件
$('#btnUpload').on('click',function(){
//讲jQ对象通过[0]转化为对象,并且通过files获取数据列表 通过自定义files接受
var files =$('#file1')[0].files;
//判断是否为空
if(files.length<=0){
alert('请上传文件')
}
//3. 向FormData中追加文件
var formdata = new FormData();
//向formdata添加数据 把files的对象传给formdata中
formdata.append('avatar',files[0]);
//发起$.ajax请求 这里只能使用$.ajax
$.ajax({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/upload/avatar',
data: formdata,
// 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
contentType: false,
// 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
processData: false,
success: function(res) {
console.log(res)
}
})
})
})
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构