如何检测在PHP的ajax跨域请求 [英] How to detect ajax cross domain request in php

查看:258
本文介绍了如何检测在PHP的ajax跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关我用正常的Ajax请求:

For the normal ajax request I use:

strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'

但是,这不跨域请求工作。

But this don't work with cross domain request.

我该怎么办?

推荐答案

EDIT2: 如果你使用jQuery.ajax功能是这样的:

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!');
}
});

然后你可以检查 $ _ SERVER ['REQUEST_URI'] 变量,或者干脆 $ _ GET ['回调'] $ _ GET ['_'] 。该REQUEST_URI将是这样的:

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

/somescript.php?somevar=somevalue&callback=jQuery172028849187534502896_1333494007273&_=1333494443880

编辑:下面的答案是,看看它是跨域与否,不检查,如果它是AJAX

在回答这个问题:如何判断一个Ajax调用是从不同的域是这样的:

The answer to the question "How to determine if an ajax-call is from a different domain" is this:

我使用jQuery.ajax电话,对我来说使用变量 $ _ SERVER ['HTTP_REFERER'] 工作正常。

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.

如果我使用的是互联网上的网页, $的价值_ SERVER ['HTTP_REFERER'] 返回,使得Ajax调用的页面的URL。因此,检查这个值可以告诉你什么是你需要知道的。

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.

这篇关于如何检测在PHP的ajax跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆