批改状态:合格
老师批语:jq的ajax操作比原生简化得太多了
熟悉jquery的$.ajax方法

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</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(): 请求数据, 实际上就是一个Html代码片断$("button:first-of-type").click(function () {$(this).after("<div>").next().load("nav.html");});// 2. $.get(). 幂操作// get: users.php?id=1// $.get(url, callback)// $.get("users.php?id=1", function (data) {$("button:nth-of-type(2)").click(function (ev) {$.get("users.php", { id: 1 }, function (data) {console.log(data);$(ev.target).after("<div>").next().html(data);});});// 3. $.post()$("button:nth-of-type(3)").click(function (ev) {$.get("users.php", { id: 1 }, function (data) {console.log(data);$(ev.target).after("<div>").next().html(data);});});// 4. $.getJSON()$("button:nth-of-type(4)").click(function (ev) {$.getJSON("users.php?id=1", function (data) {console.log(data);data = `${data.id}:${data.name},年龄:${data.age}`;$(ev.target).after("<div>").next().html(data);});});// 5. $.ajax(): 请求数据$("button:nth-of-type(5)").click(function (ev) {$.ajax({type: "get",url: "users.php",data: { id: 1 },dataType: "html",success(data) {$("button:nth-of-type(5)").after("<div>").next().html(data);console.log(data);},});});// 6. $.ajax()-jsonp: 跨域请求数据1$("button:nth-of-type(6)").click(function (ev) {$.ajax({type: "get",// fugen=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换url: "http://php.yu/test.php?id=2&fugen=?",dataType: "jsonp",jsonpCallback: "handle",});});function handle(data) {console.log(data);data = `姓名:${data.name},邮箱:${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",url: "http://php.yu/test.php?id=3&fugen=?",dataType: "jsonp",success(data) {console.log(data);data = `名称: ${data.name}, 邮箱: ${data.email}`;$(ev.target).after("<div>").next().html(data);},});});</script></body></html>
$.ajax() = $.load() + $.get() + $.post() + $.getJSON() + $.getScript()
$.ajax({
请求类型
type: “GET”,
请求的url地址
url: url,
发送数据
data: data,
希望服务器端响应返回的数据类型是什么
dataType: “json”,
请求成功的回调方法
success: callback,
});
$.ajax()-jsonp: 跨域请求数据
fugen=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号