頁面包含一個下拉選單,切換選項時無刷新請求服務端數據,並將返回的 HTML 片段替換到指定區域。後端採用 ASP.NET (`.aspx`),前端用 jQuery `$.ajax`。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>AJAX 局部刷新演示</title>
<script src="js/jquery.js" type="text/javascript"></script>
</head>
<body>
<select id="lucky1" onchange="return duoduo();">
<option value="1">第一期</option>
<option value="2">第二期</option>
</select>
<div id="duoduo">你好</div>
<input type="text" id="duo" />
<script type="text/javascript">
function duoduo() {
$.ajax({
type: 'post', // 請求方式
url: 'ajax.aspx', // 服務端處理程序
data: 'data=' + $("#lucky1").val(), // 發送參數
dataType: 'html', // 預期返回 HTML 片段
success: function(msg) {
// 成功回調:msg 為服務端返回的 HTML 字符串
document.getElementById("duoduo").innerHTML = msg;
// 或 $("#duoduo").html(msg);
},
error: function() {
alert('請求失敗,請稍後重試');
}
});
}
</script>
</body>
</html>
// ajax.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
string param = Request.Params["data"];
if (param == "1") {
Response.Write("<a href='https://www.baidu.com'>第一期</a>");
} else if (param == "2") {
Response.Write("<a href='https://www.baidu.com'>第2期</a>");
}
Response.End(); // 重要:結束響應,避免輸出頁面其餘 HTML
}
| 參數 | 說明 |
|---|---|
type | `GET` 或 `POST`,默認 GET |
url | 請求地址 |
data | 發送數據:字符串 `key=val&key2=val2` 或對象 `{key:val, key2:val2}` |
dataType | 預期返回類型:`xml, json, jsonp, script, html, text`。指定後 jQuery 會自動解析並傳給 success 回調 |
success | 成功回調函數,參數為解析後的數據 |
error | 失敗回調 (jqXHR, textStatus, errorThrown) |
beforeSend | 發送前鉤子,可修改 headers、顯示 loading |
complete | 完成後回調(無論成敗),隱藏 loading 等 |
// POST
$.post('ajax.aspx', { data: $("#lucky1").val() }, function(html) {
$("#duoduo").html(html);
});
// GET
$.get('ajax.aspx', { data: $("#lucky1").val() }, function(html) {
$("#duoduo").html(html);
});
$("#duoduo").load("ajax.aspx", { data: $("#lucky1").val() }, function(response, status, xhr) {
if (status === "error") alert("加載失敗:" + xhr.status + " " + xhr.statusText);
});
`.load(url, data, callback)` 直接將返回內容填入選中元素,內部自動處理 `html` 類型。