问题
For the normal ajax request I use:
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
But this don't work with cross domain request.
How can I do?
回答1:
Edit2: If you're using jQuery.ajax function in this way:
var request = $.ajax({
url: "http://somesite.com/somescript.php?somevar=somevalue",
dataType: "jsonp",
jsonp: 'callback',
success: function(data) {
alert('Done!');
}
});
Then you can check the $_SERVER['REQUEST_URI']
variable, or simply $_GET['callback']
and $_GET['_']
. The REQUEST_URI will look like this:
/somescript.php?somevar=somevalue&callback=jQuery172028849187534502896_1333494007273&_=1333494443880
Edit: The answer below is to find out if it is cross-domain or not, not checking if it is AJAX
The answer to the question "How to determine if an ajax-call is from a different domain" is this:
I'm using the jQuery.ajax call, and for me using the variable $_SERVER['HTTP_REFERER']
works fine.
If I'm using a page on my local computer, this superglobal returns an empty string.
If I'm using a page on the internet, the value of $_SERVER['HTTP_REFERER']
returns the URL of the page that made the ajax call. So checking the value of this can tell you what you need to know.
回答2:
use $_SERVER['HTTP_ORIGIN'] to get the request domain
回答3:
you can use php's getallheaders() function. you can check the host entry
来源:https://stackoverflow.com/questions/9997714/how-to-detect-ajax-cross-domain-request-in-php