摘要:
Ajax(Asynchornous JavaScript and XML)
主要API -----XMLHttpRequest
不同瀏覽器Ajax API不同 (jQuery幫助解決了)
不可跨域訪問,但出現了一個技術CORS
一、Key Concepts 關鍵概念
1.GET和POST
最常用的兩種提交到服務器方法(還要其他五種,delete。。。不記得了)
GET:地址欄可以看到傳入到服務器參數值鍵值對。。。。。
POST:有些數據可以抓包看,通常不會緩存在瀏覽器。。。。。
2.Data Types 數據類型
1)text
傳送簡單的字符串
2)html
傳輸html代碼塊到頁面
3)script
添加新的腳本JavaScript到頁面
4)json
傳輸json格式的數據,可以包括數組,字符串,對象
5)jsonp
從另一個域傳輸json數據
6)xml
使用xml數據傳輸數據
3.A is for Asyncharonous ——A代表異步
Ajax默認異步處理,所以只能通過異步回調函數來處理響應
var response;
$.get( "foo.php", function( r ) {
response = r;
});
console.log( response ); // undefined
$.get( "foo.php", function( response ) {
console.log( response ); // server response
});
4.Same-Origin Policy and JSONP
一般情況下,Ajax請求只在同一協議,端口,域名下執行請求,jQuery可以解決
注意,IE10以下不支持跨域的AJax請求訪問
使用JSONP可以通過js寫甲苯實現跨域訪問,避免上面的侷限
5.Ajax and Firebug (webkit觀察)
二、jQuery's Ajax-Related Methods關於jQuery的Ajax方法
所有方法的核心 $.ajax()
1.$.ajax() 詳細介紹http://api.jquery.com/jQuery.ajax/
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "post.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$( "<h1>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\">").html( json.html ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});
在請求的時候,需要告訴請求的數據格式,防止出現響應錯誤,收不到正確的服務器數據格式,如:需要請求json數據格式,那麼頭部,需要寫上 application/json
2.$.ajax()Options 選項
常用的有下面幾個,詳細的選項介紹:http://api.jquery.com/jQuery.ajax/
1)async
默認爲true,如果想同步執行請求,設置false即可。但是,設置成false後,你的請求直到收到響應後纔會去執行其他代碼塊
2)cache
緩存,是否設置,默認true,對所有的數據類型dataType有效
3)done
如果請求成功,將運行回調函數,該函數將接受響應的數據(json格式轉換爲js對象),同時,其他數據都是原類型
4)fail
如果出現錯誤,運行該回調函數
5)always
不管請求失敗還是成功,該回調函數都會運行
6)context
回調函數運行的範圍
7)data
將要發送到服務器的數據,可以是對象,也可以是查詢字符串
8)dataType
期望從服務器返回的數據類型,如果沒有明確指定的話,jQuery將根據響應的MIME來確定
9)jsonp
當執行JSONP請求的時候需要發送查詢字符串的回到名稱,默認就是”callback”
10)timeout
超時,單位毫秒,即等待多長服務器響應時間視爲失敗
11)traditional
設置爲true則將使用jQu1.4參數序列化風格,詳細見http://api.jquery.com/jQuery.param/
12)type
請求方式,"POST" 或者"GET",默認爲“GET”,其他方式比如"DELETE"也可以,但是可能有些瀏覽器不支持而已
13)url
請求地址URL,是$.ajax()中必須要配置的選項,其他選項都是可選配置的
3.Convenience Methods 常用簡便方法
只需要簡單配置一些選項就可以完成異步請求
1)$.get
給提供的URL執行GET請求
2)$.post
給提供的URL執行POST請求
3)$.getScript
給頁面添加js腳本
4)$.getJSON
執行GET提交請求,期望返回JSON格式,在不同情況下,該方法將會返回下面這些參數,依次是:
(1)url
請求的URL,必須的
(2)data
(3)success callback
(4)data type
// Using jQuery's Ajax convenience methods
// Get plain text or HTML
$.get( "/users.php", {
userId: 1234
}, function( resp ) {
console.log( resp ); // server response
});
// Add a script to the page, then run a function defined in it
$.getScript( "/static/js/myScript.js", function() {
functionFromMyScript();
});
// Get JSON-formatted data from the server
$.getJSON( "/details.php", function( resp ) {
// Log each key in the response data
$.each( resp, function( key, value ) {
console.log( key + " : " + value );
});
});
4.$.fn.load
.load()方法是jQuery ajax所有方法中唯一一個供選擇器調用的方法,去填充選擇的元素裏面的內容
// Using .load() to populate an element
$( "#newContent" ).load( "/foo.html" );
// Using .load() to populate an element based on a selector
$( "#newContent" ).load( "/foo.html #myDiv h1:first", function( html ) {
alert( "Content updated!" );
});
三、Ajax and Forms
1.Serialization
1).serialize()
.serialize()方法序列化表單的數據爲一個查詢字符串,必須要有一個name屬性,
// Turning form data into a query string
$( "#myForm" ).serialize();
// Creates a query string like this:
// field_1=something&field2=somethingElse
2).serializeArray()
發送一個數據對象,該方法更方便
// Creating an array of objects containing form data
$( "#myForm" ).serializeArray();
// Creates a structure like this:
// [
// {
// name : "field_1",
// value : "something"
// },
// {
// name : "field_2",
// value : "somethingElse"
// }
// ]
2.Client-side validate客戶端驗證
主要用在提交表單前驗證,當然也可以在服務器端驗證
// Using validation to check for the presence of an input
$( "#form" ).submit(function( event ) {
// If .required's value's length is zero
if ( $( ".required" ).val().length === 0 ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});
// Validate a phone number field
$( "#form" ).submit(function( event ) {
var inputtedPhoneNumber = $( "#phone" ).val();
// Match only numbers
var phoneNumberRegex = /^\d*$/;
// If the phone number doesn't match the regex
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});
3.Prefiltering
在發送請求錢修改ajax選項
// Using a proxy with a prefilter
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.crossDomain ) {
options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
options.crossDomain = false;
}
});
// Using the optional dataTypes argument
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
// Do all of the prefiltering here, but only for
// requests that indicate a dataType of "JSON" or "script"
});
四、Working with JSONP
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell YQL what we want and that we want JSON
data: {
q: "select title,abstract,url from search.news where query=\"cat\"",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
五、Ajax Events Ajax事件
// Setting up a loading indicator using Ajax Events
$( "#loading_indicator" )
.ajaxStart(function() {
$( this ).show();
})
.ajaxStop(function() {
$( this ).hide();
});