通過 jQuery AJAX 方法,能夠使用 HTTP Get 和 HTTP Post 從遠程服務器上請求文本、HTML、XML 或 JSON - 同時能夠把這些外部數據直接載入網頁的被選元素中。
(1) load()方法
load() 方法從服務器加載數據,並把返回的數據放入被選元素中。
$(selector).load(URL,data,callback);
必需的 URL 參數規定您希望加載的 URL。
可選的 data 參數規定與請求一同發送的查詢字符串鍵/值對集合。
可選的 callback 參數是 load() 方法完成後所執行的函數名稱。
(2) ajax()方法
ajax() 方法通過 HTTP 請求加載遠程數據。
(3) get()方法
get()方法通過 HTTP GET 請求從服務器上請求數據。
$.get(URL,callback);
必需的 URL 參數規定您希望請求的 URL。
可選的 callback 參數是請求成功後所執行的函數名。
(4)POST()方法
post() 方法通過 HTTP POST 請求從服務器上請求數據。
$.post(URL,data,callback);
必需的 URL 參數規定您希望請求的 URL。
可選的 data 參數規定連同請求發送的數據。
可選的 callback 參數是請求成功後所執行的函數名。
具體代碼如下:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<style type="text/css">
#divframe{border: 1px solid #999999;width: 500px;margin: 0 auto;}
.loadTitle{background: #cccccc;height: 30px;}
</style>
<script>
$(function(){
//1.使用load方法
// $("#btn").click(function(){
// //加載整個頁面
// //$("#ajaxTip").load("aa.html");
// //加載頁面中的某一個元素
// $("#ajaxTip").load("aa.html #userinfo");
// });
//2.使用AJAX
// $("#btn").click(function(){
// htmlobj = $.ajax({url:"aa.html #userinfo",async:false});
// $("#ajaxTip").html(htmlobj.responseText);
// });
//3.get方法
// $("#btn").click(function(){
// htmlobj = $.get("hello.txt",function(){
// $("#ajaxTip").html(htmlobj.responseText);
// });
// });
//4.post方法
$("#btn").click(function(){
$.post("hello.txt",
function(data){
$("#ajaxTip").html("獲取的數據爲:<br/>"+data);
});
});
});
</script>
</head>
<body>
<div id="divframe">
<div class="loadTitle">
<input type="button" value="獲取數據" id="btn"/>
</div>
<div id="ajaxTip">
</div>
</div>