XMLHttpRequest简称xhr,是浏览器提供的Javascript对象。之前我们使用的都是jQuery中的Ajax,现在我们使用原生JS的Ajax
目录
1 GET请求
1.1 不带参数请求
先看服务
前端请求
- xhr.open()中可以写大写的GET,也可以写小写的GET
- xhr.readyState与xhr.status写死就行,如果请求成功就需要这两个条件
xhr.readyState代表请求的状态,4代表请求已经完成了,除了4之外还有下面这几种状态
1.2 带参数请求
先看服务,当你传入data1和data2后,服务会将两个值变成整数然后加和,之后返回给你
get请求直接将要传递的东西放在查询字符串中就可以了,无论什么框架带参数的get请求数据实质上都是以查询字符串的形式传递的
2 URL的编码与解码
url地址中只允许出现字母,标点符号,数字,想是中文这种字符会被自动编码
比如说你在百度上搜索 我 这个汉字,实质上就会编码为%E6%88%91,一般来讲一个汉字就对应着三个百分号值
2.1 编码 encodeURI()
2.2 解码 decodeURI()
3 POST请求
服务
请求
post请求需要使用setRequestHeader()设置请求头,这个是固定写法,setRequestHeader()必须放在open()的后面,send()的前面
post要发送的数据要写在send()中
4 模拟jQuery中的Ajax函数
我们只考虑get与post的情况,需要处理的地方就是将传入的data对象转变为查询字符串的形式,判断是get还是post,除此之外简单弄一弄就行了
<!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">
<title>Document</title>
</head>
<body>
</body>
<script>
function myAjax(resquest_obj) {
xhr = new XMLHttpRequest()
if (/^GET$/i.test(resquest_obj.type)) {
send_str = ''
for (i in resquest_obj.data) {
send_str = send_str + i + '=' + resquest_obj.data[i] + '&'
}
send_str = send_str.slice(0,-1)
resquest_obj.url = resquest_obj.url + '?' + send_str
xhr.open(resquest_obj.type,resquest_obj.url)
xhr.send()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resquest_obj.success(xhr.responseText)
}
}
}
else if (/^POST$/i.test(resquest_obj.type)) {
xhr.open(resquest_obj.type,resquest_obj.url)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
send_str = ''
for (i in resquest_obj.data) {
send_str = send_str + i + '=' + resquest_obj.data[i] + '&'
}
send_str = send_str.slice(0,-1)
xhr.send(send_str)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resquest_obj.success(xhr.responseText)
}
}
}
}
</script>
</html>
搞一个服务测一下,get是两个数相加,post是两个数相乘
get
post