使用XMLHttpRequest对象发送post和get请求
效果展示:
代码展示:
<!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>
<script>
// 1,使用xhr发送get请求
//创建一个XMLHttpRequest()对象
var xhr = new XMLHttpRequest();
//调用open()函数,指定请求方式和请求地址
xhr.open('get','http://www.liulongbin.top:3006/api/getbooks?id=1');
//调用send()函数发送ajax请求
xhr.send();
//监听事件onreadystatechange
xhr.onreadystatechange = function () {
if(xhr.readyState === 4&&xhr.status === 200)
{
//代码运行到这里,get请求非常成功
//注意这里的responseText就是响应回来的数据
console.log(xhr.responseText);
}
}
// 2,使用xhr发送post请求
//创建一个XMLHttpRequest对象
var xhr2 = new XMLHttpRequest();
//调用open()函数,指定请求方式和地址
xhr2.open('post','http://www.liulongbin.top:3006/api/addbook');
//设置Content-Type
xhr2.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//调用send()函数
xhr2.send('bookname=aaa&author=aaaa&publisher=aaaa');
//监听事件
xhr2.onreadystatechange = function () {
if(xhr2.readyState === 4&&xhr2.status === 200)
{
//代码运行到这里,get请求非常成功
//注意这里的responseText就是响应回来的数据
console.log(xhr2.responseText);
}
}
</script>
</body>
</html>
注意事项:
1,注意get和post请求的方式的区别:
2,最后拿到请求体:
var data = xhr2.responseText
3,在发送post请求传入参数时,注意参数字符串的写法。