PHP如何傳遞Ajax成功或失敗的狀態(tài)?HTTP Status Codes可以實現(xiàn)
May 26, 2016 am 08:19 AM一般處理Ajax 回應(yīng)時會傳送的信息種類有:數(shù)據(jù)、成功信息、錯誤信息、失敗信息以及處理狀態(tài),傳遞的信息種類并不一致,再加上除了數(shù)據(jù)之外,通常還希望能傳遞處理狀態(tài),這種情況大部分會選擇是以JSON 的方式傳遞這兩個信息,以下是常見的幾種格式:
但以執(zhí)行狀態(tài)跟操作行為作一個歸納,可以區(qū)分以下幾種傳遞結(jié)果:
{ code: 1, msg: "OK" } { success: true , result: "data" , errorMsg: "" } { status: 'success' , result: [], errorMsg: "" } //...
但以執(zhí)行狀態(tài)跟操作行為作一個歸納,可以區(qū)分以下幾種回傳結(jié)果:
數(shù)據(jù)操作 HTTP Method 成功 錯誤/失敗
讀取(Read) GET 數(shù)據(jù) 錯誤/失敗信息
新增 (Create) ?POST 成功信息 錯誤/失敗信息
修改 (Update)
刪除 (Delete)
從上面的歸納可以看出規(guī)律性,接著只要有方法可以傳送處理的狀態(tài),以及能夠區(qū)分數(shù)據(jù)的種類,其實就單純很多,而HTTP Status Codes 就是用來傳遞HTTP 的處理狀態(tài),如果利用這個方式來傳遞自定義的處理狀態(tài),這樣HTTP Content 就可以很單純傳遞數(shù)據(jù),讓數(shù)據(jù)格式不受限于JSON,還可以使用其他格式(text, xml, html),而且XMLHttpRequest 本身就有處理HTTP Status Codes 的能力,而jQuery.ajax 也有提供error status 的處理,所以可以利用這個來定義狀態(tài)的處理,在HTTP Status Codes 有幾個已經(jīng)定義狀態(tài),很適合用來傳遞處理狀態(tài)的信息:
400Bad Request錯誤的請求適用在表單內(nèi)容的錯誤,如必填欄位未填、Email 格式錯誤
403Forbidden沒有權(quán)限,被禁止的適用在沒有登錄或權(quán)限不足
500Internal Server Error內(nèi)部服務(wù)器錯誤適用在程序的錯誤
jQuery 接收信息的范例,代碼如下:
$.ajax({ type: "POST" , url: document.location, success: function (data, textStatus, jqXHR) { alert(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); } });
PHP 傳遞錯誤信息的范例,代碼如下:
if (php_sapi_name() == 'cgi' ){ header ( "Status: 400 Bad Request" ); } else { header ( "HTTP/1.0 400 Bad Request" ); } exit ( "儲存失敗!!" );
C# MVC 傳遞錯誤信息的范例,代碼如下:
Response.TrySkipIisCustomErrors = true ; Response.StatusCode = 400; return Content( "儲存失敗!!" );
文章鏈接:
隨便收藏,請保留本文地址!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
