jQuery 提供 $.ajax()、$.post()、$.get()、$.load(),支援 html、text、json、xml 等 dataType。
$.post() 取得純文字/HTML$.post('test.jsp',
{ name: 'cssrain', time: '2008/01/21' },
function(data) {
alert('回傳資料: ' + data); // data 為字串
}
);
$.load() 載入片段並取得回呼參數$('#loadajax').load('https://www.111cn.net .post',
function(responseText, textStatus, xhr) {
// this 指向 #loadajax DOM 元素
console.log('狀態:', textStatus);
}
);
$.ajax() 完整 JSON 範本$.ajax({
type: 'GET',
dataType: 'json',
url: 'BackHandler.ashx',
data: 'pageIndex=' + pageIndex,
beforeSend: function() { $('#load').show(); },
complete: function() { $('#load').hide(); },
success: function(msg) {
var data = msg.table; // 假設後端回傳 { table: [...] }
$.each(data, function(i, n) {
var row = $('#template').clone();
row.find('#OrderID').text(n.訂單ID);
row.find('#CustomerID').text(n.客戶ID);
// ... 其他欄位綁定
row.attr('id', 'ready').appendTo('#datas');
});
},
error: function(xhr, status, err) {
console.error('AJAX 失敗:', status, err);
}
});
若後端不回傳任何內容(或回傳空白),切勿設定 dataType: 'json',否則 jQuery 會嘗試解析導致 parsererror。
$.ajax({
type: 'POST',
url: 'index.php',
data: { id: uid },
// 不寫 dataType,jQuery 會自動判斷或視為 text
success: function() {
alert(1); // 只需知道成功即可
},
error: function() {
alert(0);
}
});
function check_email() {
var email = $('#reg_mail').val();
var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
if (!reg.test(email)) return;
$.get('register.php', { check_name: 'email', check_value: email }, function(json) {
if (json === 'ok') {
$('#res_mail').html('此 email 可註冊!');
} else {
$('#res_mail').html('此 email 已被註冊!');
}
});
}
dataType: 'json' 要求回傳合法 JSON,空白或 HTML 會拋錯。'text'。error 回呼,方便除錯。dataType: 'jsonp')。