以下用同一個頁面示範幾種常見的取資料寫法。
<script type="text/javascript" src="jquery-1.3.2.min.js"></script> <div id="divMsg">Hello World!</div>
$("#divMsg").load("https://localhost:8012/t.php", { "resultType": "html" });
resultType 可用的值有:"xml"、"html"、"script"、"json"、"jsonp"、"text"。
<input type="button" id="bnajax" value="ajax" onclick="ajaxTest()" />
<script type="text/javascript">
function ajaxTest() {
$.post("https://localhost:8012/t.php", { "txt": "123" }, function (data) {
$("#divMsg").html(data);
});
}
</script>
function test(access_url, tipE) {
$.post(access_url, {
first: "test1",
second: "test2"
}, function (data) {
if (data.success) {
$('#' + tipE).html('處理成功');
} else {
$('#' + tipE).html(data.msg);
}
}, 'json' // 指定回應型別為 JSON,data 才會被自動解析成物件
);
}
這裡的 data 是伺服器回傳的值,格式為 JSON,例如 {success: true, msg: "測試成功"}。當然也可以改成 text、xml 等其他型別。
若想用 GET,只要把 post 換成 get 即可,就這麼簡單。
需要提醒的是,範例中 onclick="ajaxTest()" 這種內聯寫法在現代實務中已不建議,改用 $("#bnajax").on("click", ajaxTest) 讓結構與行為分離會更好維護。另外,https://localhost:8012 是寫死的絕對路徑,實際專案應改用相對路徑或 <base> 標籤管理,避免環境切換時到處改網址。
最後,若回傳的內容會被插入到頁面中,而內容可能含有使用者輸入,務必先轉義或使用 .text(),以免成為 XSS 的入口。