HTTP的狀態碼有很多種,主要有1xx(臨時響應)、2xx(成功)、3xx(已重定向)、4xx(請求錯誤)以及5xx(服務器錯誤)五個大類,每個大類還對應一些具體的分類。平時我們接觸比較多的是200、400、500等。
這里我們主要討論一下狀態碼204,在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.
意思等同於請求執行成功,但是沒有數據,瀏覽器不用刷新頁面.也不用導向新的頁面。如何理解這段話呢。還是通過例子來說明吧,假設頁面上有個form,提交的url為http-204.htm,提交form,正常情況下,頁面會跳轉到http-204.htm,但是如果http-204.htm的相應的狀態碼是204,此時頁面就不會發生轉跳,還是停留在當前頁面。另外對於a標簽,如果鏈接的頁面響應碼為204,頁面也不會發生跳轉。
所以對於一些提交到服務器處理的數據,只需要返回是否成功的情況下,可以考慮使用狀態碼204來作為返回信息,從而省掉多余的數據傳輸。
