The example in this article describes how PHP determines whether it is an ajax request. Share it with everyone for your reference, the details are as follows:
Let’s first talk about how to distinguish when the front end uses jQuery:
When jQuery issues an ajax request, it will add a header named X-Requested- With information, the information content is: XMLHttpRequest
You can use $_SERVER["HTTP_X_REQUESTED_WITH"] on the backend to obtain it. (Note: The dash is replaced by an underscore, which is not case-sensitive)
From this, we can judge whether it is an ajax request:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ // ajax 请求的处理方式 }else{ // 正常请求的处理方式 };
When using native JavaScript to issue an ajax request, we can also add information to the header to facilitate back-end students to distinguish. The method is as follows:
var xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","test.php",true); xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"); xmlhttp.send();
The above is the content of the method of PHP judging whether it is an ajax request. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!