jQuery Ajax 完整示例
百度 jQuery CDN
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
1. $.ajax
$.ajax({
// 请求地址
url : "http://localhost:8080/user/list/",
// 请求方式(大小写不敏感)
type : "get",
// 是否异步(默认true)
async: true,
// 发送到服务器的数据
data : {},
// 预期服务器返回的数据类型(如果返回的是json字符串,会自动封装成json对象)
dataType: "json",
// 设置请求头
contentType: "application/json;charset=UTF-8",
//请求成功
success : function(res) {
console.log(res);
},
//请求失败,包含具体的错误信息
error : function(err){
console.log("错误:", err);
}
});
2. $.get
格式:$.get(URL, data, callback);
// 1. 请求json文件,忽略返回值
$.get('http://localhost:8080/user/list/');
// 2. 请求json文件,传递参数,忽略返回值
$.get('http://localhost:8080/user/list/', {name:"tom", age: 14});
// 3. 请求json文件,请求成功拿到返回值
$.get('http://localhost:8080/user/list/', function(res) {
console.log(res);
});
// 4. 请求json文件,传递参数,拿到返回值
$.get('http://localhost:8080/user/list/', {name:"tom", age: 14}, function(res) {
console.log(res);
});
3. $.post
格式:$.post(URL, data, callback);
// 1. 请求json文件,忽略返回值
$.post('http://localhost:8080/user/list/');
// 2. 请求json文件,传递参数,忽略返回值
$.post('http://localhost:8080/user/list/', {name:"tom", age: 14});
// 3. 请求json文件,请求成功拿到返回值
$.post('http://localhost:8080/user/list/', function(res) {
console.log(res);
});
// 4. 请求json文件,传递参数,拿到返回值
$.post('http://localhost:8080/user/list/', {name:"tom", age: 14}, function(res) {
console.log(res);
});
4. $getJSON
格式:$.getJSON(URL, data, callback);
要求返回的数据格式必须是json格式
// 1. 请求json文件,忽略返回值
$.getJSON('http://localhost:8080/user/list/');
// 2. 请求json文件,传递参数,忽略返回值
$.getJSON('http://localhost:8080/user/list/', {name:"tom", age: 14});
// 3. 请求json文件,请求成功拿到返回值
$.getJSON('http://localhost:8080/user/list/', function(res) {
console.log(res);
});
// 4. 请求json文件,传递参数,拿到返回值
$.getJSON('http://localhost:8080/user/list/', {name:"tom", age: 14}, function(res) {
console.log(res);
});

浙公网安备 33010602011771号