1. 程式人生 > >HTTP 204和205的應用

HTTP 204和205的應用

之前和人討論過這個問題,,, 今天感冒在家休息, 就回憶了一下, 整理如下.

我們很多的應用在使用Ajax的時候, 大多數情況都是詢問型操作, 比如提交資料, 則Ajax只是期待伺服器返回:

{status: 0, message:""} //status 0代表成功, 非零的時候, message中包含出錯資訊.

我們知道HTTP的狀態碼, 2xx都是表示成功, 而HTTP的204(No Content)響應, 就表示執行成功, 但是沒有資料, 瀏覽器不用重新整理頁面.也不用導向新的頁面.

在HTTP RFC 2616中關於204的描述如下:

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

類似的還有205 Reset Content, 表示執行成功, 重置頁面(Form表單).

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. This response is primarily intended to allow input for actions to take place via user input, followed by a clearing of the form in which the input is given so that the user can easily initiate another input action.

於是, 當有一些服務, 只是返回成功與否的時候, 可以嘗試使用HTTP的狀態碼來作為返回資訊, 而省掉多餘的資料傳輸, 比如REST中的DELETE和如上所述的查詢式Ajax請求.

最後說說205, 205的意思是在接受了瀏覽器POST請求以後處理成功以後, 告訴瀏覽器, 執行成功了, 請清空使用者填寫的Form表單, 方便使用者再次填寫,

總的來說, 204適合多次對一個Item進行更新, 而205則適合多次提交一個系列的Item.

但, 請注意, 目前還沒有一個瀏覽器支援205, 大部分的瀏覽器, 都會把205當做204或者200同樣對待.