PHP determines the principle of Ajax requests:
When sending an AJAX request, we can create a custom header message by XMLHttpRequest This object, in the jquery framework, for the $.ajax, $.get, or $.post methods that request the content of the Web page. It will pass a http_x_requested_with parameter to the server, PHP is in the header layer to determine whether the AJAX request, corresponding to $_server[' Http_x_requested_with '] judgment.
/* * * whether the current request is an AJAX request * * @access public * @return BOOL */ function Isajax () { returnisset($_serverstrtolower($_server[' Http_x_requested_with ']) = = ' XMLHttpRequest '; }
- In general $_server[' Http_x_requested_with ') is XMLHttpRequest by default
- $_server[' Http_x_requested_with ' can also be custom created, using Xmlhttprequest.setrequestheader (name,value); Reference article:/http www.skygq.com/2011/01/04/php-check-request-from-ajax-or-normal/
PHP cross-domain issues when judging Ajax requests:
If this is a cross-domain, the above isajax is completely incorrect. Cross-domain Problem reference: "Several problems encountered by $.getjson" use $.getjson to implement cross-domain, but detect whether Ajax is always false, and try to $get (see: $.get implementation returns parsing JSON data and JSONP cross-domain) after no results , consider using the universal $ajax method, see the documentation for Ajax:
If a script or JSONP type is specified, then when the data is received from the server, the <script> tag is actually used instead of the XMLHttpRequest object. In this case, $.ajax () no longer returns a XMLHttpRequest object, and it does not pass an event handler, such as Beforesend.
Explain:
Ajax can only specify JSONP format data, this is not XMLHttpRequest object, even if you customize a $_server[' Http_x_requested_with '] is meaningless
The solution:
For cross-domain scenarios, Getjson or Ajax (JSONP) can use the Accept Request header format to determine
PHP side corresponding $_server[' http_accept ']
Jsonp's request is generally: Text/javascript, Application/javascript, */*
JSON request: Application/json, Text/javascript, */*
A simple judgment for Ajax requests across domain conditions:
Switch($_server[' Http_accept ']){ Case' Application/json, Text/javascript, */* '://JSON Format Break; Case' Text/javascript, Application/javascript, */* '://JavaScript or JSONP format Break; Case' Text/html, */* '://HTML Format Break; Case' Application/xml, Text/xml, */* '://XML Format Break; }
PHP Judge Ajax Request: Http_x_requested_with