First let’s talk about how to distinguish when the front end uses jQuery:
When jQuery issues an ajax request, it will add a piece of information named X-Requested-With to the request header. The information content is: XMLHttpRequest
You can use $_SERVER["HTTP_X_REQUESTED_WITH"] on the backend to obtain it. (Note: The dash has been replaced by an underscore, and it is not case-sensitive)
From this, we can judge whether it is an ajax request like this:
<span>//</span><span> php 判断是否为 ajax 请求 http://www.cnblogs.com/sosoft/</span> <span>if</span>(<span>isset</span>(<span>$_SERVER</span>["HTTP_X_REQUESTED_WITH"]) && <span>strtolower</span>(<span>$_SERVER</span>["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"<span>){ </span><span>//</span><span> ajax 请求的处理方式 </span> }<span>else</span><span>{ </span><span>//</span><span> 正常请求的处理方式 </span> };
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:
<span>1</span> <span>var</span> xmlhttp=<span>new</span><span> XMLHttpRequest(); </span><span>2</span> xmlhttp.open("GET","test.php",<span>true</span><span>); </span><span>3</span> xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"<span>); </span><span>4</span> xmlhttp.send();
Here we also add X_REQUESTED_WITH information to the header, which is consistent with jQuery. Of course, you can also change it to other information to distinguish.
OK, what are the benefits of making the distinction? Let’s talk about two examples:
1. When the js file is not loaded, the user clicks a button or link, and what should be an ajax request becomes a normal request. Based on judgment, the backend does not output the json data during ajax, but jumps. , which is also a form of graceful degradation.
2. [A page] uses ajax to log in, [B page] uses the normal method to log in. If there is no distinction, the backend needs to write almost the same code twice, but with the distinction, the repeated code can be Eliminate.
Enable PHP pseudo-static http://www.cnblogs.com/sosoft/p/3549336.html