GET请求
<script>
const btn = document.getElementById('kssb'); //绑定按钮
btn.onclick = function() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url');//open()参数:请求类型 URL
xhr.send();
xhr.onreadystatechange = function() {
//当请求完毕时
if (xhr.readyState == 4) {
//判断请求是否成功
if (xhr.status == 200 && xhr.status < 300) {
//请求成功事件
alert(xhr.response);
}
}
}
}
</script>
POST请求
<script>
const btn = document.getElementById('kssb'); //绑定按钮
btn.onclick = function() {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'url');
xhr.send(a=1&b=3&c=5);//POST请求数据
xhr.onreadystatechange = function() {
//当请求完毕时
if (xhr.readyState == 4) {
//判断请求是否成功
if (xhr.status == 200 && xhr.status < 300) {
//请求成功事件
alert(xhr.response);
}
}
}
}
</script>