1.代码
1.1前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AJAX POST 请求</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
<script
crossorigin="anonymous"
src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"
></script>
</head>
<body>
<button>发送get请求</button>
<button>发送past请求</button>
<button>通用方法发送请求</button>
<div id="result"></div>
</body>
<script>
$("button")
.eq(0)
.click(function () {
$.get(
"http://127.0.0.1:8000/server",
{
a: 1, b: 2 },
function (data) {
console.log("发送get请求 :"+ data);
},
"json"
);
});
$("button")
.eq(1)
.click(function () {
$.post(
"http://127.0.0.1:8000/server",
{
a: 1, b: 2 },
function (data) {
console.log("发送post请求 :"+ data);
},
"json"
);
});
$("button")
.eq(2)
.click(function () {
$.ajax({
url: "http://127.0.0.1:8000/server",
data: {
a: 1, b: 2 },
type: "GET",
dataType: 'json',
timeout: 2000,
headers:{
header1:1,
header2:2,
},
success: function (data) {
console.log("发送通用请求 :"+ data);
},
error: function(data){
console.log('出错拉!')
}
});
});
</script>
</html>
1.2服务端代码
const express = require("express");
const app = express();
app.all("/server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
const data = {
name: "lixv000",
};
let str = JSON.stringify(data);
response.send(str);
});
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中……");
});
2.代码讲解
app.all("/server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
const data = {
name: "lixv000",
};
let str = JSON.stringify(data);
response.send(str);
});
- app.all,意思是不管是get请求还是post请求都可以接收
$("button")
.eq(0)
.click(function () {
$.get(
"http://127.0.0.1:8000/server",
{
a: 1, b: 2 },
function (data) {
console.log("发送get请求 :"+ data);
},
"json"
);
});
- $(“button”)相当于document.getElementsByTagName(“button”),eq则是根据索引选择具体的结点。
$.get(
"http://127.0.0.1:8000/server",
{
a: 1, b: 2 },
function (data) {
console.log("发送get请求 :"+ data);
},
"json"
);
- $.get()是jquery封装的用来发送get请求的方法(发送post请求则为$.post());第一个参数是请求的url;第二个参数是请求参数;function(data)是对请求返回的值进行处理的函数;"json"则规定返回的数据格式为json对象。
$.ajax({
url: "http://127.0.0.1:8000/server",
data: {
a: 1, b: 2 },
type: "GET",
dataType: 'json',
timeout: 2000,
headers:{
header1:1,
header2:2,
},
success: function (data) {
console.log("发送通用请求 :"+ data);
},
error: function(data){
console.log('出错拉!')
}
});
- $.ajax()是jquery封装的通用的发送get或者post请求的方法,里面有很多中参数,常见的有(url:请求地址;data:请求阐述;type:请求方式;dataType:数据返回格式;timeout:超时时间毫秒;headers:请求头;success:请求成功调用的函数;error:请求失败调用的函数)
3.运行结果
