PHP method to determine whether it is an ajax request

黄舟
Release: 2023-03-06 06:54:02
Original
1110 people have browsed it

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{ 
  // 正常请求的处理方式 
};
Copy after login



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();
Copy after login



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)!

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