批改状态:合格
老师批语:异步编程对js来说是致命的技术, 一定要掌握
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Ajax</title><script src="jquery-3.4.1.js"></script><style>.body{display: grid;gap: 15px;}.body > .button{width: 100px;height: 50px;font-size: 15px;}</style></head><body><button type="button">load()请求数据</button><button type="button">$.get()</button><button type="button">$.post()</button><button type="button">$.getJSON()请求JSON数据</button><button type="button">$.get()</button><button type="button">6. $.ajax()-jsonp-跨域请求数据1</button><button type="button">7. $.ajax()-jsonp-跨域请求数据2</button></body></html><script>// 1. load(): 加载html片断$("button:first-of-type").click(function () {$(this).after("<div>").next().load("nav.html");});//2.get():以get方式从服务器获取数据$("button:nth-of-type(2)").click(function (ev) {$.get("users.php", { id: 2 }, function (data) {$(ev.target).after("<div>").next().html(data);});});//3.post():以post方式从服务器获取数据$("button:nth-of-type(3)").click(function (ev) {$.post("users.php", { id: 2 }, function (data) {$(ev.target).after("<div>").next().html(data);});});// 4. $.getJSON():接口返回的大多是JSON$("button:nth-of-type(4)").click(function (ev) {$.getJSON("users.php?id=2", function (data) {var res = data.id + ": " + data.name + ", " + data.age + "岁";$(ev.target).after("<div>").next().html(res);});});// 5. $.ajax(): 终级方法, 实际上大家只需要掌握这一个方法$("button:nth-of-type(5)").click(function (ev) {$.ajax({type: "GET",url: "users.php",data: { id: 2 },dataType: "html",success: function (data) {$(ev.target).after("<div>").next().html(data);},});});// 6. $.ajax()-jsonp-1:跨域请求$("button:nth-of-type(6)").click(function (ev) {$.ajax({type: "GET",url: "http://php11.demo/0527/test.php?jsonp=?&id=2",dataType: "jsonp",success: function (data) {cl(data);var data = JSON.parse(data);cl(data);var data ="<p>" +data.title +"</p><p>" +data.user.name +", 邮箱:" +data.user.email +"</p>";$(ev.target).after("<div>").next().html(data);},});});// 7. $.ajax()-jsonp-2:跨域请求$("button:last-of-type").click(function (ev) {$.ajax({type: "GET",url: "http://php11.demo/0527/test.php?jsonp=?&id=2",dataType: "jsonp",jsonpCallback: "handle",});});function handle(data) {cl(data);var data = JSON.parse(data);cl(data);var data ="<p>" +data.title +"</p><p>" +data.user.name +", 邮箱:" +data.user.email +"</p>";$("button:last-of-type").after("<div>").next().html(data);}</script>
本节课我们学习了Ajax方法,通过本节课的学习学到了Ajax方法,知道通过什么方式进行数据请求。有助于后期的实战应用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号