First of all, say the principle:
When sending an AJAX request, we can create a custom header message by XMLHttpRequest this object
If you are using a native Ajax method, that is, an Ajax method that is not wrapped with jquery or another JS framework, the code is as follows:
?
1 |
xmlHttpRequest.setRequestHeader( "request_type" , "ajax" ); |
Oh yes, you must know how xmlhttprequest this object was created, right? Amount You're not kidding, are you? You do not know-that I advise you still do not understand, rest assured that you do not understand him is also OK, below I tell you how to use in jquery, it is more simple AH ~ ~
The jquery $.ajax () method makes it easy to create our custom header information before sending an AJAX request.
?
123456789101112 |
$.ajax({
type :
"GET"
,
url : base_url +
‘php_check_ajax_request/get_user_list.html‘
,
beforeSend :
function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(
"request_type"
,
"ajax"
);
},
success :
function
(data){
$(
"#user_list"
).html(data);
$tip.hide();
$button.attr(
‘disabled‘
,
true
);
}
});
|
The above code, is the code I use in the demo, there are several lines, you do not fear, to your attention is an address, found the beforesend it? Yes, there it is, Xmlhttprequest.setrequestheader ("Request_type", "Ajax"); This code is to create a custom variable in the header message "Request_ Type ".
Well, in this case, you should already be sending Ajax requests to the header information to add custom information.
Next I'll tell you that it's pretty easy to get this information in PHP.
As I defined before the variable "Request_type", then in PHP should be obtained
?
1 |
$_SERVER [ ‘HTTP_REQUEST_TYPE‘ ] |
Look at the above code, I think so wise you must have found the law, right, yes, that is, "request_type" This variable all uppercase (must be capitalized), and then add a "http_" prefix, and then $_server this super variable to find it.
?
123 |
if (isset( $_SERVER [ ‘HTTP_REQUEST_TYPE‘ ]) && $_SERVER [ ‘HTTP_REQUEST_TYPE‘ ] == "ajax" ){ //ajax提交 } else { //非ajax提交 } |
The above code is the PHP program to determine whether the request is not an AJAX request.
"Request_type" This variable is our custom, oh, if you like, you can also change her to your favorite name, such as "Test", "Is_ajax" ....
Based on the above description ~ ~ Do you understand?
hehe ~ ~ Do not understand also does not matter ~ ~ because you can move your finger slightly, leave your question ~
Reprint from Dream ploughing
PHP Determines whether a request is an AJAX request or an ordinary request