First, how to differentiate the front-end when using jQuery:
When jQuery sends an ajax request, a message named X-Requested-With is added to the request header. The message content is XMLHttpRequest.
You can use $ _ SERVER ["HTTP_X_REQUESTED_WITH"] On the backend to obtain the data. (Note: The dashes are replaced by underscores, which are case-insensitive)
Therefore, we can determine whether the request is an ajax request:
// Php determine if it is an ajax request http://www.cnblogs.com/sosoft/if (isset ($ _ SERVER ["HTTP_X_REQUESTED_WITH"]) & strtolower ($ _ SERVER ["HTTP_X_REQUESTED_WITH"]) = "xmlhttprequest ") {// ajax request processing method} else {// normal request processing method };
When using native JavaScript to send an ajax request, we can also add information to the header to facilitate the differentiation of backend students. The method is as follows:
1 var xmlhttp=new XMLHttpRequest(); 2 xmlhttp.open("GET","test.php",true); 3 xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"); 4 xmlhttp.send();
Here we also add the X_REQUESTED_WITH information to the header, which is consistent with that of jQuery. Of course, you can also change it to other information for differentiation.
OK. What are the advantages of differentiation? Here are two examples:
1. when the js file is not loaded, the user clicks a button or link, which is supposed to be a normal request for ajax requests. the backend jumps without outputting json data in ajax Based on judgment, this is also a form of graceful degradation.
2. [page A] uses ajax for logon and [page B] for normal logon. If there is no distinction, the backend needs to write almost identical code twice, you can remove duplicate codes.
Open a pseudo-static http://www.cnblogs.com/sosoft/p/3549336.html for PHP