1、实现GET请求
<button>发送请求</button>
//创建一个button按钮,用来测试
<script>
document.querySelector('button').onclick = function () {
// 1. 创建 xhr 对象
let xhr = new XMLHttpRequest();
// 2. 设置监听事件(监听Ajax执行到哪一步了),并且在完成后,接收响应结果
xhr.onreadystatechange = function () {
let res = xhr.responseText; // 这里单独讲
console.log(res);
}
// 3. open方法,设置请求方式和URL
// xhr.open('GET', 'http://www.itcbc.com:3006/api/getbooks?参数=值&参数=值');
xhr.open('GET', 'http://www.itcbc.com:3006/api/getbooks?appkey=laotang');
// 4. send方法,发送请求
xhr.send();
}
</script>
2、实现POST请求
<button>发送</button>
<script>
document.querySelector('button').onclick = function () {
// 1. 创建 xhr 对象
let xhr = new XMLHttpRequest();
// 2. 设置监听事件,监听ajax的变化。等到ajax完成后,接收响应结果
xhr.onreadystatechange = function () {
let res = xhr.responseText;
console.log(res);
}
// 3. open方法,设置请求方式和URL
xhr.open('POST', 'http://www.itcbc.com:3006/api/addbook');
// 4. 调用 setRequestHeader 设置请求头
// xhr.setRequestHeader(名字, 值);
// xhr.setRequestHeader('fasongren', 'laotang');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 5. send方法,发送请求
// xhr.send('参数=值&参数=值&参数=值');
let b = '史记';
xhr.send(`bookname=${b}&author=司马迁&publisher=北京出版社&appkey=laotang`);
}
</script>