思考 Ajax請求

1. 什麼是ajax 

ajax是asynchronous javascript and XML的簡寫,中文翻譯是異步的javascript和XML,這一技術能夠向服務器請求額外的數據而無須卸載頁面,會帶來更好的用戶體驗。雖然名字中包含XML,但ajax通信與數據格式無關。

ajax技術的核心是XMLHttpRequest 對象(簡稱xhr)

IE7+,Firfox,Opera,Chrome,safari都支持原生的xhr對象,在這些瀏覽器中創建xhr對象要像下面這樣使用XMLHttpRequest構造函數。

var  xhr=new XMLHttpRequest();

在使用xhr對象時,要調用的第一個方法是open(),它接受3個參數:要發送的請求的類型(get,post,等),請求的URL,和表示是否異步請求的布爾值。

注:調用open()方法並不會真正發送請求,而只是啓動一個請求以備發送。

xhr.open("get","example.php",false); 

要發送特定請求,必須像下面這樣,調用send()方法,參數null 表示作爲請求主體發送的數據。調用send()方法後,請求就會被分派到服務器。

xhr.send(null);

xhr對象的屬性

(1)responseText:作爲響應主體被返回的文本。

(2)responseXML:若響應內容的類型:text/xml 或application/xml ,這個屬性中將保存包含着響應數據的xml dom文檔

(3)status:響應的http狀態

(4)statusText:http狀態的說明

  (5) readyState:該屬性表示請求/響應過程的當前活動階段,這個屬性可取的值如下

      0: 未初始化,尚未調用open()方法

      1: 啓動,已經調用open()方法,但尚未調用send ()方法

      2: 發送,已經調用send()方法,但尚未收到響應

      3: 接收,已經接收到部分響應數據

      4: 完成,已經接收到全部響應數據,而且已經可以中客戶端使用了。

      只要readyState屬性的值由一個值變成另一個值,都會觸發一次readystatechange事件,可以利用這個事件來檢測每次狀態變化後readystate的值。

      xhr.onreadystatechange=function(){

              if(xhr.readyState==4){

                    if((xhr.status>=200 && xhr.status<300) || xhr.status==304}{

                              console.log(xhr.responseText);

                    } else{

                             console.log("requst was un successful:"+xhr.status);

                     }

                }

        }

在接收到響應之前,還可以調用abort()方法來取消異步請求,如下所示:

xhr.abort();

調用這個方法後,xhr對象會停止觸發事件。而且也不允許訪問任何與響應有關的對象屬性。


/*********************************************************************************************************************/

AngularJS 提供了一個類似jQuery的$.ajax的對象,用於異步請求。
在AngularJS中對異步操作是推崇至極的,所以$http的操作都是異步的不像jquery.ajax裏還提供了async參數。

對於官網的$http對象的總結和使用。


用法:

$http(config);

參數:

config (常用的參數標紅,翻譯了一下)

config object

Object describing the request to be made and how it should be processed. The object has following properties:

  • method – {string} – HTTP method (e.g. 'GET', 'POST', etc)  ------------------  http交互方法:GET/POST 兩種
  • url – {string} – Absolute or relative URL of the resource that is being requested. ------------------  URL傳輸地址
  • params – {Object.<string|Object>} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters.    ------------------  Map 類型的參數,傳輸給後臺
  • data – {string|Object} – Data to be sent as the request message data. ------------------  要求傳入的參數 
  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
  • xsrfHeaderName – {string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName – {string} – Name of cookie containing the XSRF token.
  • transformRequest – {function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. See Overriding the Default Transformations
  • transformResponse –{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default TransformationjqLiks
  • paramSerializer - {string|function(Object<string,string>):string} - A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the $injector, which means you can create your own serializer by registering it as a service. The default serializer is the $httpParamSerializer; alternatively, you can use the$httpParamSerializerJQLike
  • cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. ------------------  緩存,設爲true的時候,默認的$ HTTP緩存將用於緩存GET請求,否則,創建Factory緩存實例.
  • timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
  • responseType - {string} - see XMLHttpRequest.responseType.


返回: 一個httpPromise對象(一般只用data和status)

HttpPromise

Returns a promise object with the standard then method and two http specific methods: success and error. Thethen method takes two arguments a success and an error callback which will be called with a response object. Thesuccess and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.  ------------------  返回數據
  • status – {number} – HTTP status code of the response. ------------------  返回狀態。等於200時爲成功,否則失敗。
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.  ------------------  用於生成請求的配置對象,原來傳入的參數等。
  • statusText – {string} – HTTP status text of the response. ------------------  返回的狀態文本

方法:

get(url, [config]);         快捷的方法來執行GET請求。

post(url, data, [config]);  快捷的方法來執行POST請求。

put(url, data, [config]);

patch(url, data, [config]);


jsonp(url, [config]);

head(url, [config]);

delete(url, [config]);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章