AJAX学习笔记
Ajax 即 Asynchronous Javascript And XML(异步 JavaScript 和 XML),是指⼀种创建交互式⽹⻚应⽤的⽹⻚开发技术。原生JS提供了XMLHttpRequest对象来实现这种技术
XHR
xhr,全称为XMLHttpRequest,用于与服务器交互数据,是ajax
功能实现所依赖的JS对象
重要的属性
属性 | 类型 | 功能 |
---|---|---|
onreadystatechange | 函数(事件) | 当xhr对象的readyState 属性发生改变时触发该事件 |
open | 函数 | 初始化xhr对象,调用完成后readyState 从0变成1XMLHttpRequest.open(method:string,url:string,async:boolean,username?:string,password?:string) |
setRequestHeader | 函数 | 设置请求的自定义标头header,通常在一些POST请求场景需要通过此函数指定标头 Content-Type |
send | 函数 | 发送请求,XMLHttpRequest.send(body) ,接收一个参数,表示本次请求Body中携带的数据 |
readyState | 字段 | 0:请求未初始化(还没有调用 open()) 1:请求已经建立,但是还没有发送(还没有调用 send())。 2:请求已发送,正在处理中(通常现在可以从响应中获取内容头)。 3:请求在处理中;通常响应中已有部分数据可用了,但是服务器还没有完成响应的生成。 4:响应已完成;您可以获取并使用服务器的响应了。 |
status | 字段 | 服务器响应的http状态码 示例:200:OK |
GET请求
let url = "http://localhost:62322/api/values?id=1" //请求地址,可以传递QueryString参数
let xhr = new XMLHttpRequest()
xhr.open("get",url,true)
xhr.setRequestHeader("my-header","headervalue")
xhr.send(null)//不传递数据
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200)
{//当响应完成且返回的状态码为200
}
}
POST请求
json
- 需要指定
Content-Type
为application/json;charset=UTF-8
let url = "http://localhost:62322/api/values" //请求地址
let xhr = new XMLHttpRequest()
xhr.open("post",url,true)
//表明请求体内的数据类型是json
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8")
let json = {"value1":1,"value2":2};
xhr.send(JSON.stringify(json))
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200)
{//当响应完成且返回的状态码为200
}
}
form表单
-
需要指定
Content-Type
为application/x-www-form-urlencoded
-
参数用
&
符号进行分割
let url = "http://localhost:62322/api/values"
let xhr = new XMLHttpRequest()
xhr.open("post",url,true)
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send("value1=1&value2=2") //发送两个表单参数 value1 和 value2
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200)
{
}
}
上传文件
function uploadFile() {
let url = "http://localhost:62322/api/values/UploadFile"
let el = document.getElementById("file")
if (el.files.length <= 0) {
return alert('请选择要上传的文件!')
}
let xhr = new XMLHttpRequest()
let fd = new FormData()
fd.append("imgfile",el.files[0])
xhr.open("post",url,true)
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4 && xhr.status === 200) {
}
}
xhr.send(fd)
}
<input type="button" onclick="uploadFile()" value="上传" />
<input id="file" type="file" value="选择文件" />