:这三种方法都是jQuery中规定的Ajax方法中一种与服务器交换数据的请求类型。
- $.get() 使用
使用方式: $.get(url, [data], [callback], [type])
URL为请求地址(必填),callback为回调函数(可填)
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text,
样例:
$.get('http://127.0.0.1:8000/jquery-server', function (data) {
$('.a').html(data.name);
console.log(data);
}, 'json')
- $.post() 使用
使用方式: $.post(url, [data], [callback], [type])
URL为请求地址(必填)
callback为回调函数(可填)
data为请求发送的数据(可填)
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text,
样例 :
$.post('http://127.0.0.1:8000/jquery-server', function (data) {
$('.a').html(data.name);
console.log(data);
}, 'json')
- $.ajax() 使用
该方法可以执行精确的需求控制,通常用于其他方式不能完成的请求
样例
$.ajax({
// 请求类型
type: 'GET',
// 请求url
url: 'http://127.0.0.1:8000/jquery-server',
// 响应体结果
dataType: 'json',
// 超时设置
timeout: 2000,
// 成功回调
success: function (data) {
$('.a').html(data.name);
console.log(data);
},
// 失败回调
error: function () {
console.log('出错啦 !!');
},
});
- 以上三种实现ajax请求都基于下面 server.js代码 app.all 可以接受(get ,post请求)
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
// 3.创建路由规则
app.all('/jquery-server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
// 用 Cors 来解决跨域问题
response.setHeader('Access-Control-Allow-Headers', '*');
response.setHeader('Access-Control-Allow-Method', '*')
// 设置响应体
let data = {
name: '方敬'
}
response.send(JSON.stringify(data));
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动,8000端口....");
});
5.打开浏览器 输入 :http://127.0.0.1:8000/jquery-server