Judge by adding xmlhttp information to the header."/> Judge by adding xmlhttp information to the header.">

Home  >  Article  >  Backend Development  >  How to determine if it is an ajax request in php

How to determine if it is an ajax request in php

藏色散人
藏色散人Original
2021-09-01 09:28:113663browse

How to determine whether it is an ajax request in php: 1. Determine through the "if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]){...}" method; 2. By adding xmlhttp information to the header. Judgment.

How to determine if it is an ajax request in php

The operating environment of this article: Windows7 system, PHP7.1 version, Dell G3 computer

How to judge php Is it an ajax request?

PHP determines whether it is an AJAX request

Let’s first talk about how to distinguish when the front end uses jQuery:

When jQuery issues an ajax request, it will be in the request Add a piece of information named , not case sensitive)

From this, we can judge whether it is an ajax request like this:

// php 判断是否为 ajax 请求  http://www.cnblogs.com/sosoft/
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();

Here we also add X_REQUESTED_WITH information to the header, which is consistent with jQuery. Of course you can also You can change it to other information to distinguish.

OK, what are the benefits of distinguishing? Let’s talk about two examples:

1. When the js file is not loaded At the end, the user clicked a button or link, and what was supposed to be an ajax request became a normal request. Based on judgment, the backend did not output the json data during ajax, but jumped. This 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, duplicates can be The code disappears.

Turn on PHP’s pseudo-static.

Recommended: "

PHP Video Tutorial

"

The above is the detailed content of How to determine if it is an ajax request in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn