Home > Article > Backend Development > How to implement php to determine whether it is an ajax request
This article mainly introduces the method of PHP judging whether it is an ajax request. It analyzes the principle of ajax request and the background judgment skills for ajax request in the form of examples. Friends who need it can refer to it
Let’s talk first How to distinguish when using jQuery on the front end:
When jQuery issues an ajax request, a message named X-Requested-With will be added to the header of the request. The content of the message 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 entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
phpFile contains directory configuration open_basedir usage and performance
php Implement the method of calling ffmpeg to obtain video information
php PDO implementation to determine whether the connection is Available methods
The above is the detailed content of How to implement php to determine whether it is an ajax request. For more information, please follow other related articles on the PHP Chinese website!