async:是否異步執行AJAX請求,默認為true,千萬不要指定為false;
method:發送的Method,缺省為'GET',可指定為'POST'、'PUT'等;
contentType:發送POST請求的格式,默認值為'application/x-www-form-urlencoded; charset=UTF-8',也可以指定為text/plain、application/json;
data:發送的數據,可以是字符串、數組或object。如果是GET請求,data將被轉換成query附加到URL上,如果是POST請求,根據contentType把data序列化成合適的格式;
headers:發送的額外的HTTP頭,必須是一個object;
dataType:接收的數據格式,可以指定為'html'、'xml'、'json'、'text'等,缺省情況下根據響應的Content-Type猜測。
var jqxhr = $.ajax('/api/categories', {
dataType: 'json'
});
// 請求已經發送了
'use strict';
function ajaxLog(s) {
var txt = $('#test-response-text');
txt.val(txt.val() + '\n' + s);
}
$('#test-response-text').val('');
var jqxhr = $.ajax('/api/categories', {
dataType: 'json'
}).done(function (data) {
ajaxLog('成功, 收到的數據: ' + JSON.stringify(data));
}).fail(function (xhr, status) {
ajaxLog('失敗: ' + xhr.status + ', 原因: ' + status);
}).always(function () {
ajaxLog('請求完成: 無論成功或失敗都會調用');
});
<body>
<textarea id="test-response-text" rows="10" style="width: 90%; margin: 15px 0; resize: none;">
響應結果:
</textarea>
</body>
get
var jqxhr = $.get('/path/to/resource', {
name: 'Bob Lee',
check: 1
});
第二個參數如果是object,jQuery自動把它變成query string然后加到URL后面,實際的URL是:
/path/to/resource?name=Bob%20Lee&check=1
post
第二個參數默認被序列化為application/x-www-form-urlencoded
var jqxhr = $.post('/path/to/resource', {
name: 'Bob Lee',
check: 1
});
name=Bob%20Lee&check=1作為POST的body被發送
getJSON
var jqxhr = $.getJSON('/path/to/resource', {
name: 'Bob Lee',
check: 1
}).done(function (data) {
// data已經被解析為JSON對象了
});