Home >Backend Development >PHP Tutorial >How does PHP determine whether it is an AJAX request?
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请求 }
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);
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();
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
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!