Most JavaScript frameworks, such as jquery and Mootools, send additional HTTP_X_REQUESTED_WITH header information when sending Ajax requests. the header is an ajax request, therefore, you can detect Ajax requests on the server.
Most JavaScript frameworks, such as jquery and Mootools, send additional HTTP_X_REQUESTED_WITH header information when sending Ajax requests. the header is an ajax request, therefore, you can detect Ajax requests on the server side.
1. pass the _ GET parameter to determine the webpage request.
The url is passed as follows: *******. php? Ajax
Php's judgment:
- If (isset ($ _ GET ['Ajax ']) {
-
- ... This is an ajax request, and then...
-
- }
-
- Else {
-
- ... This is not an ajax request, and then...
-
- }
This implementation method is very poor, and it is quite easy to forge. there is no difference between judgment and non-judgment, so another method that we think is very scientific is proposed, this method does have some learning value.
Php obtains the xmlHttpRequest interpretation in the system variables.
First, you must use jquery and Js to send ajax requests. ajax, $. get, or $. when the post method requests the webpage content, it will pass a HTTP_X_REQUESTED_WITH parameter to the server. The value of this parameter is xmlHttpRequest.
The Js code is as follows:
- BeforeSend: function (XMLHttpRequest ){
-
- XMLHttpRequest. setRequestHeader ("X-Requested-With", "XMLHttpRequest ");
-
- };
The parameter name is X-Requested-With, and the parameter value is XMLHttpRequest. you can define it as needed. when obtaining the parameter name in Php, you must add an http character in front of the parameter name. The code is as follows:
- If (! Emptyempty ($ _ SERVER ['http _ X_REQUESTED_WITH ']) & strtolower ($ _ SERVER ['http _ X_REQUESTED_WITH']) = 'xmlhttprequest ')
- {
- // If AJAX Request Then
- } Else {
- // Something else
- }
1. if
If your jquery request uses iframe to open a webpage, the HTTP_X_REQUESTED_WITH parameter will not be passed. that is to say, you cannot determine the request type.
2. Internet Explorer 5 and Internet Explorer 6 versions $. ajax, $. get, or $. the post method does not automatically send the HTTP_X_REQUESTED_WITH parameter to the header information, because the parameter cannot be obtained in php for judgment, unless you construct the XMLHttpRequest object and send it to the php script, it is equivalent to implementing ajax functions with the most primitive JavaScript code. in this way, the ajax framework originally encapsulated by jquery will become meaningless.