PHP determines if it is an AJAX request

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.