Home  >  Article  >  PHP Framework  >  How does Yii2 determine whether it is an Ajax request?

How does Yii2 determine whether it is an Ajax request?

Guanhui
GuanhuiOriginal
2020-06-12 13:51:353591browse

How does Yii2 determine whether it is an Ajax request?

#Yii2 How to determine whether it is an Ajax request?

Yii2 method of judging Ajax requests: Just judge the "isAjax" attribute in the request class. If it is true, it is an Ajax request, otherwise it is not an Ajax request. The principle is to judge "$_SERVER" "X-Requested-With" is "XMLHttpRequest".

Sample code

Yii::$app->request->isAjax
 
if (Yii::$app->request->isAjax) {
    echo "是";
}

PHP native judgment

jquery will add an X-Requested- to the request header With information, the information content is XMLHttpRequest, so that PHP can use the $_SERVER global array to determine whether it is an ajax request

if (isset($_SERVER["HTTP_X_REQUESTED_WITH"] && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"] == 'xmlhttprequest')){
    // 是ajax请求
} else {
    // 不是ajax请求
}

Recommended tutorial: "Yii Tutorial"

The above is the detailed content of How does Yii2 determine whether it is an Ajax request?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn