ajax发送
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="res"></div>
<script>
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = "json";
xhr.open("GET", "http://localhost:8000/json-server");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
//手动对数据进行转换
// let data = JSON.parse(xhr.response)
// console.log(data)
//自动转换
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
};
</script>
</body>
</html>
jq发送
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h2>jQuery发送Ajax请求</h2>
<script>
$.ajax({
//url
url: "http://localhost:8000/jquery-server",
//参数
data: { a: 100, b: 222 },
//请求类型
type: "GET",
//响应体结果
dataType: "json",
//成功的回调
success: function (data) {
console.log(data);
},
//超时时间
timeout: 2000,
//失败的回调
error: function () {
console.log("出错了");
},
//头信息设置
headers: {
c: 300,
d: 400,
},
});
</script>
</body>
</html>
axios发送
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
</head>
<body>
<h2>jQuery发送Ajax请求</h2>
<script>
axios({
method: "GET",
url: "your url",
//url参数
params: {
},
//头信息
headers: {
},
//请求体参数
data: {
},
}).then((response) => {
console.log(response);
});
</script>
</body>
</html>
fetch发送
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
fetch("http://localhost:8000/fetch-server", {
//请求方法
method: "POST",
//请求头
headers: {
name: "hanser",
},
//请求体
body: "name=admin&pd=admin",
})
.then((Response) => {
console.log(Response);
return Response.text();
})
.then((Response) => {
console.log(Response);
});
</script>
</body>
</html>