一、AJAX loda() 方法
load() :从服务器加载数据,并把返回的数据放入被选元素中
- URL:加载的url
- data:规定与请求一同发生的查询字符串键值对集合
- callback:回调函数,load完成后所执行的函数
callback回调函数可以设置不同的参数:
1、responseTxt:包含调用成功时的结果内容
2、statusTxt:调用的状态
3、xhr:XMLHttpRequest 对象
// 语法
$(selector).load(URL,data,callback);
// 获取demo_test.txt文件中 id="p1" 的元素的内容,加载到指定的div中
$("#div1").load("demo_test.txt #p1");
// callback
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部内容加载成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
//1.当前文件中要插入的地方使用此结构:
<div class="include" file="***.html"></div>
//2.***.html中放入内容,用html格式仅仅因为会有编辑器的书写辅助。。
//3.代码:
$(".include").each(function() {
if (!!$(this).attr("file")) {
var $includeObj = $(this);
// html就是loca调用成功时的结果内容(responseTxt)
$(this).load($(this).attr("file"), function(html) {
$includeObj.after(html).remove(); //加载的文件内容写入到当前标签后面并移除当前标签
})
}
});
// 或者在index文件里只写重复部分,剩下的一股脑放各自单独文件 load() 进来~
二、get() 和 post()
两者在客户端和服务端进行请求-响应的常用方法:GET 和 POST
两者的比较:https://www.runoob.com/tags/html-httpmethods.html
- GET:从指定的资源请求数据
- POST:向指定的资源提交要处理的数据(也可以用于从服务器获取数据)
2.1 jQuery $.get() 方法
// 语法
$.get(URL,callback);
// 从服务器上的一个文件中读取数据
$("button").click(function(){
$.get("demo_test.php",function(data,status){
alert("数据: " + data + "\n状态: " + status);
});
});
// 下面是demo_test.php
<?php
echo '这是个从PHP文件中读取的数据。';
?>
回调函数callback:有两个参数:
1、请求成功后返回的内容
2、请求的状态
2.2、jQuery $.post() 方法
// 语法
$.post(URL,data,callback);
// $.post()连同请求一起发送数据
$("button").click(function(){
$.post("/try/ajax/demo_test_post.php",
{
name:"菜鸟教程",
url:"http://www.runoob.com"
},
function(data,status){
alert("数据: \n" + data + "\n状态: " + status);
});
});
// demo_test_post.php
<?php
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$url = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo '网站名: ' . $name;
echo "\n";
echo 'URL 地址: ' .$url;
?>
data:规定连同请求发送的数据(类似于url?data)
callback:回调函数,请求成功后所执行的函数名
回调函数有两个参数:
- data:存有请求页面的内容
- status:存有请求的状态