一般在开发中,我们采用在jQuery中发送AJAX请求。
请求方式
get 请求
$.get(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text, _default。
post 请求
$.post(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text,
通用方法发送请求
$.ajax({
url:****,
data:***,
type:***…
})
案例
<!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>jQuery 发送Ajax请求</title>
</head>
<body>
<button>GET</button><button>POST</button><button>常规方法发送</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
// 1.GET请求
$('button').eq(0).on('click', function () {
$.get('http://localhost:8000/jQuery-server', { a: 100, b: 100 }, function (data) {
console.log(data);
}, 'json')
})
// 2.POST请求
$('button').eq(1).on('click', function () {
$.post('http://localhost:8000/jQuery-server', { a: 100, b: 100 }, function (data) {
console.log(data);
}, 'json')
})
// 3.常规方法发送
$('button').eq(2).on('click', function () {
$.ajax({
url: 'http://localhost:8000/jQuery-server',
data: {
a: 100,
b: 100
},
type: 'GET',
success: function (data) {
console.log(data);
}
})
})
</script>
</body>
</html>
server.js
// 1.引入express
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
app.all('/jQuery-server', (request, response) => {
// request 是对请求报文的封装
// response 是对响应报文的封装
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
// 设置响应体
let data = { name: 'xy', age: 21 };
data = JSON.stringify(data);
response.send(data);
});
// 4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已经启动,8000端口监听中...');
})