-
$.ajax
jQuery.ajax( [settings ] )
$.ajax({
url: 'xxx.php',
method: 'GET',
data: {
name: 'Byron',
age: 24,
sex: 'Male'
}
}).done(function(result){
console.log(result);
}).fail(function(jqXHR, textStatus){
consloe.log(textStatus);
});
這樣我們就發(fā)送了一個get請求
方法提供了幾個常用的setting
async:默認(rèn)設(shè)置下,所有請求均為異步請求(也就是說這是默認(rèn)設(shè)置為 true )。如果需要發(fā)送同步請求,請將此選項(xiàng)設(shè)置為 false
beforeSend:請求發(fā)送前的回調(diào)函數(shù),用來修改請求發(fā)送前jqXHR對象,此功能用來設(shè)置自定義 HTTP 頭信息,等等。該jqXHR和設(shè)置對象作為參數(shù)傳遞
cache:如果設(shè)置為 false ,瀏覽器將不緩存此頁面。注意: 設(shè)置cache為 false將在 HEAD和GET請求中正常工作。它的工作原理是在GET請求參數(shù)中附加"_={timestamp}"
context:這個對象用于設(shè)置Ajax相關(guān)回調(diào)函數(shù)的上下文。 默認(rèn)情況下,這個上下文是一個ajax請求使用的參數(shù)設(shè)置對象
data:發(fā)送到服務(wù)器的數(shù)據(jù)。將自動轉(zhuǎn)換為請求字符串格式。GET 請求中將附加在 URL 后面,POST請求作為表單數(shù)據(jù)
headers:一個額外的{鍵:值}對映射到請求一起發(fā)送。此設(shè)置會在beforeSend 函數(shù)調(diào)用之前被設(shè)置 ;因此,請求頭中的設(shè)置值,會被beforeSend 函數(shù)內(nèi)的設(shè)置覆蓋
method:HTTP 請求方法 (比如:"POST", "GET ", "PUT",1.9之前使用“type”)
了解了這些參數(shù),使用jQuery處理ajax請求就簡單了
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
除了這個方法,jQuery還提供了一些額外的方法
-
$.get
jQuery.get( [settings] ) / jQuery.post( [settings ] )
這兩個方法專門用來處理get和post請求
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
簡單示例
$.get('/ajax.json').done(function(ret){
console.log(ret)
})
顯示結(jié)果:

-
$.getJSON
jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )
使用一個HTTP GET請求從服務(wù)器加載JSON編碼的數(shù)據(jù),這是一個Ajax函數(shù)的縮寫,這相當(dāng)于:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
示例:
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("/ajax.json",function(result){
$.each(result, function(i, field){
$("p").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>獲得 JSON 數(shù)據(jù)</button>
<p></p>
</body>
