<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jQuery-Ajax</title>
<style>
body {
display: grid;
gap: 15px;
}
button {
padding: 0.5em;
text-align: left;
}
button span {
color: red;
}
button:hover {
background-color: lightcyan;
cursor: pointer;
}
</style>
</head>
<body>
<button>1. load(): 请求数据</button>
<button>2. $.get(): 请求数据</button>
<button>3. $.post(): 请求数据</button>
<button>4. $.getJSON(): 请求JSON数据</button>
<button>5. $.ajax(): 请求数据</button>
<button>6. $.ajax()-jsonp: 跨域请求数据1</button>
<button>7. $.ajax()-jsonp: 跨域请求数据2</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
// 1.load 请求数据
$("button:first-of-type").click(function () {
$(this).after("<div>").next().load("nav.html");
});
// 2. get 请求数据
// 语法:$.get(url,callback)
$("button:nth-of-type(2)").click(function (ev) {
// 两种方式:
// 1.url地址内添加查询条件等
// $.get("users.php?id=1",callback)
// 2.将条件单独列出,作为查询条件(幂{ id: 1 }操作)
// $.get("users.php",{id:1},callback)
$.get("users.php", { id: 1 }, function (data) {
$(ev.target).after("<div>").next().html(data);
});
});
// 3.post请求数据
// POST,应该将数据封装到一个对象中发送
$("button:nth-of-type(3)").click(function (ev) {
$.post("users.php", { id: 1 }, function (data) {
$(ev.target).after("<div>").next().html(data);
});
});
// 4. $.getJSON()
$("button:nth-of-type(4)").click(function (ev) {
$.getJSON("users.php?id=2", function (data) {
// 从服务器端拿回的json数据会自动解析为JS对象,js.parent()
data = `序号:${data.id} 姓名:${data.name} 年龄:${data.age}`;
$(ev.target).after("<div>").next().html(data);
});
});
// 5.$.ajax()
// $.ajax() = $.load() + $.get() + $.post() + $.getJSON() + $.getScript()
$("button:nth-of-type(5)").click(function (ev) {
$.ajax({
// 5.1:声明请求类型
type: "GET",
// 5.2 说明请求的url地址
url: "users.php",
// 5.3发送的数据
data: { id: 1 },
// 5.4 希望服务器返回的数据类型
dataType: "html",
// 5.5 成功的回调处理方法
success(data) {
$(ev.target).after("<div>").next().html(data);
},
});
});
// 6. $.ajax()-jsonp: 跨域请求数据1
$("button:nth-of-type(6)").click(function (ev) {
$.ajax({
type: "GET",
// jsonp=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换
url: "http://blog.io/test.php?id=2&jsonp=?",
dataType: "jsonp",
jsonpCallback: "handle",
});
});
function handle(data) {
console.log(data);
data = `Name: ${data.name}, Email: ${data.email}`;
$("button:nth-of-type(6)").after("<div>").next().html(data);
}
// 7. $.ajax()-jsonp: 跨域请求数据2
$("button:last-of-type").click(function (ev) {
$.ajax({
type: "GET",
// jsonp=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换
url: "http://blog.io/test.php?id=3&jsonp=?",
dataType: "jsonp",
success(data) {
console.log(data);
data = `Name: ${data.name}, Email: ${data.email}`;
$("button:last-of-type").after("<div>").next().html(data);
},
});
});
</script>
</body>
</html>
最后修改:2020 年 11 月 13 日 01 : 36 PM
© 允许规范转载