<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装ajax</title>
<script>
function $ajax({ method = "get", url, data, success, error }) {
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (error) {
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
if (data) {
data = querystring(data);
}
if (method == "get" && data) {
url += "?" + data;
}
xhr.open(method, url, true);
if (method == "get") {
xhr.send();
} else {
//设置请求的格式
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (success) {
// alert(2);//第二步执行
success(xhr.responseText);
}
} else {
if (error) {
error("Error:" + xhr.status);
}
}
}
}
}
function querystring(obj) {
var str = "";
for (var attr in obj) {
str += attr + "=" + obj[attr] + "&";
}
return str.substring(0, str.length - 1); //字符串提取
}
window.onload = function () {
var ogetBtn = document.getElementById("getBtn");
var opostBtn = document.getElementById("postBtn");
//get
ogetBtn.onclick = function () {
//第一步执行
$ajax({
url: "get.php",
data: {
username: "ling",
age: 12,
password: "1245"
},
success: function (result) {
// alert(3);//第三步执行
alert("get请求下载到的数据:" + result);
},
error: function (msg) {
alert(msg);
}
})
}
opostBtn.onclick = function () {
$ajax({
method: "post",
url: "post.php",
data: {
username: "ling",
age: 12,
password: "1245"
},
success: function (result) {
alert("post请求下载到的数据:" + result);
},
error: function (msg) {
alert(msg);
}
})
}
}
</script>
</head>
<body>
<button id="getBtn">get请求</button>
<button id="postBtn">post请求</button>
</body>
</html>
将get方法和post方法封装ajax
最新推荐文章于 2023-12-14 20:37:19 发布