jQuery load()方法是一种简单但功能强大的AJAX方法。jQuery中的Load()方法有助于从服务器加载数据并返回到所选元素,而无需加载整个页面。
null
语法:
$(selector).load(URL, data, callback);
参数: 该方法接受上述三个参数,如下所述:
- 网址: 它用于指定需要加载的URL。
- 数据: 它用于指定一组与请求一起发送的查询键/值对。
- 回拨: 它是可选参数,是调用load()方法后要执行的函数的名称。
返回值: 此方法使用指定的URL从服务器返回请求的数据。
例子:
极客。txt文件存储在服务器上,单击“单击”按钮后将加载该文件。极客的内容。它们是: 你好,Geeksforgeks!
项目1:
<!DOCTYPE html> < html > < head > < script src = </ script > < script > $(document).ready(function(){ $("button").click(function(){ $("#div_content").load("gfg.txt"); }); }); </ script > < style > body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </ style > </ head > < body > < div id = "div_content" > < div class = "gfg" >GeeksforGeeks</ div > < div class = "geeks" >A computer science portal for geeks</ div > </ div > < button >Change Content</ button > </ body > </ html > |
输出:
参数中还有一个额外的回调函数,它将在load()方法完成时运行。此回调函数有三个不同的参数:
- 参数1: 如果方法调用成功,它将包含内容的结果。
- 参数2: 它包含调用函数的状态。
- 参数3: 它包含XMLHttpRequest对象。
项目2:
< html > < head > < script src = </ script > < script > $(document).ready(function(){ $("button").click(function(){ $("#div_content").load("gfg.txt", function(response, status, http){ if(status == "success") alert("Content loaded successfully!"); if(status == "error") alert("Error: " + http.status + ": " + http.statusText); }); }); }); </ script > < style > body { text-align: center; } .gfg { font-size:40px; font-weight: bold; color: green; } .geeks { font-size:17px; color: black; } #div_content { font-size: 40px; font-weight: bold; color: green; } </ style > </ head > < body > < div id = "div_content" > < div class = "gfg" >GeeksforGeeks</ div > < div class = "geeks" >A computer science portal for geeks</ div > </ div > < button >Change Content</ button > </ body > </ html > |
输出: 给定代码的输出会出现一个警告框,单击按钮后会出现该框,如果内容加载成功,则会显示一条消息 “内容加载成功!” 。否则将显示错误消息。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END