For some API interfaces, it usually checks whether the request is an AJAX request, which can improve the security to a certain extent.
For some API interfaces, it usually checks whether the request is an AJAX request, which can improve the security to a certain extent.
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 determines if it is an ajax request
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
// Ajax request processing method
}else{
// Normal request handling 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:
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.php",true);
xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest");
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.