封装的简易Ajax-get,js文件
function ajax(url,success,error) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
success(xmlhttp);
} else {
error(xmlhttp);
}
}
}
}
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="myAjax.js"></script>
<script>
window.onload=function () {
var oBtn=document.querySelector("button");
oBtn.onclick=function () {
ajax(要传入的url网址,
function (xhr) {
alert(xhr.responseText);
},
function (xhr) {
alert("请求失败");
})
}
}
</script>
</head>
<body>
<button> 发送请求</button>
</body>
</html>