jquery中Ajax的load(),get()和post()方法
jQuery load() 方法
jQuery load() 方法是簡單但強大的 AJAX 方法。
load() 方法從服務器加載數據,並把返回的數據放入被選元素中。
語法:
$(selector).load(URL,data,callback);
-
必需的 URL 參數規定希望加載的 URL。
-
可選的 data 參數規定與請求一同發送的查詢字符串鍵/值對集合。
-
可選的 callback 參數是 load() 方法完成後所執行的函數名稱。
代碼示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax-load()</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("/try/ajax/demo_test.txt");
});
});
</script>
</head>
<body>
<button>獲取外部內容</button>
</body>
</html>
也可以把 jQuery 選擇器添加到 URL 參數。
下面的例子把 “demo_test.txt” 文件中 id=“p1” 的元素的內容,加載到指定的 < div> 元素中:
$("#div1").load("demo_test.txt #p1");
可選的 callback 參數規定當 load() 方法完成後所要允許的回調函數。回調函數可以設置不同的參數:
- responseTxt - 包含調用成功時的結果內容
- statusTXT - 包含調用的狀態
- xhr - 包含 XMLHttpRequest 對象
下面的例子會在 load() 方法完成後顯示一個提示框。如果 load() 方法已成功,則顯示"外部內容加載成功!",而如果失敗,則顯示錯誤消息:
$("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);
});
});
jQuery - AJAX get() 和 post() 方法
jQuery get() 和 post() 方法用於通過 HTTP GET 或 POST 請求從服務器請求數據。
兩種在客戶端和服務器端進行請求-響應的常用方法是:GET 和 POST。
- GET - 從指定的資源請求數據
- POST - 向指定的資源提交要處理的數據
GET 基本上用於從服務器獲得(取回)數據。註釋:GET 方法可能返回緩存數據。
POST 也可用於從服務器獲取數據。不過,POST 方法不會緩存數據,並且常用於連同請求一起發送數據。
jQuery $.get() 方法
$.get() 方法通過 HTTP GET 請求從服務器上請求數據。
語法:
$.get(URL,callback);
-
必需的 URL 參數規定您希望請求的 URL。
-
可選的 callback 參數是請求成功後所執行的函數名。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax-get()</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("/try/ajax/demo_test.php",function(data,status){
alert("數據: " + data + "\n狀態: " + status);
});
});
});
</script>
</head>
<body>
<button>發送一個 HTTP GET 請求並獲取返回結果</button>
</body>
</html>
jQuery $.post() 方法
$.post() 方法通過 HTTP POST 請求向服務器提交數據。
語法:
$.post(URL,data,callback);
-
必需的 URL 參數規定您希望請求的 URL。
-
可選的 data 參數規定連同請求發送的數據。
-
可選的 callback 參數是請求成功後所執行的函數名。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax-post()</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("/try/ajax/demo_test_post.php",{
name:"Ajax-post()",
url:"http://www.runoob.com"
},
function(data,status){
alert("數據: \n" + data + "\n狀態: " + status);
});
});
});
</script>
</head>
<body>
<button>發送一個 HTTP POST 請求頁面並獲取返回內容</button>
</body>
</html>