我做在我的控制器以下解析:JavaScript的響應不是狀態碼4XX
def publish
respond_to |format|
format.js do
if allowed_to_publish then
render :js => 'alert("successful");'
else
render :js => 'alert("error");'
end
end
end
end
客戶端訪問方法與一個Ajax請求。迄今爲止,這種方法很好,唯一讓我感到困惑的是響應的狀態代碼始終爲「200」。
當發生錯誤並且無法滿足請求時,根據錯誤類型它應該是4xx或5xx響應。在我的情況下,當用戶沒有輸入所有必需的細節時,publish
可能會出錯。我認爲這個正確的狀態代碼是412 precondition failed。
現在,當我改變的狀態代碼,現在不執行JavaScript:
def publish
respond_to |format|
format.js do
if allowed_to_publish then
render :js => 'alert("successful");'
else
render :js => 'alert("error");', :status => 412
end
end
end
end
客戶端獲得相同的反應,但狀態碼,並且不會再執行JavaScript。響應報頭有以下幾種:
Date Sun, 04 Sep 2011 12:29:58 GMT
Server Apache/2.2.14 (Ubuntu)
X-Powered-By Phusion Passenger (mod_rails/mod_rack) 3.0.8
X-UA-Compatible IE=Edge
Cache-Control no-cache
X-Runtime 0.176543
Status 412
Strict-Transport-Security max-age=172800, includeSubDomains
Keep-Alive timeout=15, max=100
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/javascript; charset=utf-8
和身體仍然是alert("error");
。但它不警告。這是一個瀏覽器限制(我正在使用Firefox 7b),還是可以使這與軌道工作?
如果我想讓我的JavaScript執行,我必須總是使用200
嗎?
是的,這正是我在沒有「412」響應的第一個示例中所做的。但是如果出現錯誤,它不應該用'200成功'來回應!因爲,它並不成功。但是這似乎打破了javascript解析。 – Markus
你能否請你發佈你的處理響應的JavaScript代碼? –
@markus:我會說HTTP狀態碼只是語義。它不會傷害,如果你只是返回200. – pimvdb