How does PHP determine whether it is an AJAX request?

jacklove
Release: 2023-03-27 15:16:01
Original
8730 people have browsed it

This article explains how PHP determines whether it is an AJAX request? .

Ajax request sent by Jquery

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

//php determines whether it is an ajax request

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

So this reminds me of a constant in TP that determines whether it is an ajax request, IS_AJAX

Here is a look at how this constant is defined

In ThinkPHP(3.2.2) in ThinkPHP/Library/Think/APP.class.php(Line: 49)

define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
 strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !emtpty($_POST(C('VAR_AJAX_SUBMIT')] || !empty($_GET[C('VAR_AJAX_SUBMIT')])) 
 ? true : false);
Copy after login

It can be seen that ThinkPHP uses this principle or submits it in the form.

Ajax request initiated by native js

You need to add the request header information yourself so that you can make judgments in the background.

The code for adding request headers at the front desk is:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","test.php",true);
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.send();
Copy after login

This article explains how PHP determines whether it is an AJAX request. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Solution to handling date() warning reported by PHP program

Solving concurrency in PHP development Case discovery of several implementation methods of the problem

Tutorial on quickly exporting Table data with PHP

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template