For the sake of the security of the program, in some cases we will need to detect whether a request is an AJAX request, how to judge it?
This article will briefly share the experience.
1. When using native JavaScript to make AJAX requests, we can add information to the request header to make it easier for the backend PHP program to differentiate, as follows:
var xmlhttp=new xmlhttprequest (); Xmlhttp.open ("GET", "test.php", true); Xmlhttp.setrequestheader ("X-requested-with", "XMLHttpRequest"); Xmlhttp.send ();
Here we add x_requested_with information to the head, the value is XMLHttpRequest, of course, the value here can be arbitrarily set, such as: www.phpernote.com. This can be written on the receiving side of the PHP program:
!--? php//PHP to determine if the AJAX request if (Isset ($_server[& #39; http_x_requested_with& #39;]) &&strtolower ($_server[& #39; http_x_requested_with& #39;]) ==& #39; xmlhttprequest& #39;) {//Ajax request Processing mode}else{//Normal request processing} 2. Now the more popular JS framework jquery is considered quite well, when JQuery makes an AJAX request, it adds a name called X-r to the request header. Equested-with information, the information content is: XMLHttpRequest, so the back-end PHP can also be used as the code to judge.
Note: If your jquery request is to open a Web page through an iframe, then the Http_x_requested_with parameter is not passed, meaning you have no way of judging the type of the request.