在遊戲框架1.x中,我們可以很快知道,如果請求是AJAX或不問request.isAjax()
方法,但我無法找到它的播放2.Play Framework 2.0中的isAjax()方法在哪裏?
什麼是另類或者是這種方法嗎?
在遊戲框架1.x中,我們可以很快知道,如果請求是AJAX或不問request.isAjax()
方法,但我無法找到它的播放2.Play Framework 2.0中的isAjax()方法在哪裏?
什麼是另類或者是這種方法嗎?
如果您使用JQuery Ajax的,它設置了以下要求標題:
X-Requested-With: XMLHttpRequest
以後可以訪問測試,如果呼叫通過Ajax還是沒有這樣做。
你可以把它定義爲一種方法,並在控制器中使用它:
def isAjax[A](implicit request : Request[A]) = {
request.headers.get("X-Requested-With") == Some("XMLHttpRequest")
}
+1,只需檢查是否存在x-requested標頭是不夠的,無論如何,Android 4都會發送標頭(如「com.google。 android.browser「),ajax請求與否。 – virtualeyes 2013-08-03 13:21:06
這裏是爲那些誰不使用Scala的(比如我)
/**
* Check if the request was made via Ajax or not
* @return
*/
public static Boolean isAjax() {
String requestWithHeader = "X-Requested-With";
String requestWithHeaderValueForAjax = "XMLHttpRequest";
String[] value = request().headers().get(requestWithHeader);
return
value != null &&
value.length > 0 &&
value[0].equals(requestWithHeaderValueForAjax);
}
我一個天真的Java實現我意識到這一點,我只是想知道在Play Fw中是否有與'isAjax'類似的方法,而不是每次需要知道時都要檢查這個頭文件。 – 2012-04-27 17:25:47
不,沒有,你必須檢查標題。 – 2012-04-28 12:21:35
很傷心。爲什麼他們刪除了這個方法,這非常有用?! – 2012-05-02 09:41:46