2012-04-26 206 views

回答

5

如果您使用JQuery Ajax的,它設置了以下要求標題:

X-Requested-With: XMLHttpRequest 

以後可以訪問測試,如果呼叫通過Ajax還是沒有這樣做。

+0

我一個天真的Java實現我意識到這一點,我只是想知道在Play Fw中是否有與'isAjax'類似的方法,而不是每次需要知道時都要檢查這個頭文件。 – 2012-04-27 17:25:47

+0

不,沒有,你必須檢查標題。 – 2012-04-28 12:21:35

+0

很傷心。爲什麼他們刪除了這個方法,這非常有用?! – 2012-05-02 09:41:46

4

你可以把它定義爲一種方法,並在控制器中使用它:

def isAjax[A](implicit request : Request[A]) = { 
    request.headers.get("X-Requested-With") == Some("XMLHttpRequest") 
} 
+0

+1,只需檢查是否存在x-requested標頭是不夠的,無論如何,Android 4都會發送標頭(如「com.google。 android.browser「),ajax請求與否。 – virtualeyes 2013-08-03 13:21:06

2

這裏是爲那些誰不使用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); 
}