我在一个平台上对我自己的服务器进行ajax调用,他们设置该平台阻止这些ajax调用(但我需要它从我的服务器获取数据,以显示从服务器的数据库检索的数据)。我的ajax脚本工作正常,它可以将数据发送到服务器的php脚本以允许其处理。但是,由于被"Access-Control-Allow-Origin"
阻塞,它无法取回处理过的数据
我无法访问该平台的源代码/核心。所以我不能删除脚本,它不允许我这样做。(P/S我使用了Google Chrome的控制台,发现了这个错误)
Ajax代码如下所示:
$.ajax({
type: "GET",
url: "http://example.com/retrieve.php",
data: "id=" + id + "&url=" + url,
dataType: 'json',
cache: false,
success: function(data)
{
var friend = data[1];
var blog = data[2];
$('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog);
}
});
或者,是否有与上面的ajax脚本等效的JSON
代码?我认为JSON
是被允许的。
我希望有人能帮帮我。
发布于 2018-04-23 09:10:35
使用*
是一个非常糟糕的主意,因为它会让你对跨站点脚本大开眼界。基本上,您总是想要自己的域,范围是您当前的SSL设置,还可以选择其他域。您还希望它们都作为一个标头发送。下面将始终在与当前页相同的SSL作用域中授权您自己的域,并且还可以选择包括任意数量的其他域。它会将它们都作为一个头发送,如果其他东西已经发送了它们,则覆盖前一个(S),以避免浏览器抱怨发送了多个访问控制头。
class CorsAccessControl
{
private $allowed = array();
/**
* Always adds your own domain with the current ssl settings.
*/
public function __construct()
{
// Add your own domain, with respect to the current SSL settings.
$this->allowed[] = 'http'
. ( ( array_key_exists( 'HTTPS', $_SERVER )
&& $_SERVER['HTTPS']
&& strtolower( $_SERVER['HTTPS'] ) !== 'off' )
? 's'
: null )
. '://' . $_SERVER['HTTP_HOST'];
}
/**
* Optionally add additional domains. Each is only added one time.
*/
public function add($domain)
{
if ( !in_array( $domain, $this->allowed )
{
$this->allowed[] = $domain;
}
/**
* Send 'em all as one header so no browsers grumble about it.
*/
public function send()
{
$domains = implode( ', ', $this->allowed );
header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
}
}
用法:
$cors = new CorsAccessControl();
// If you are only authorizing your own domain:
$cors->send();
// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
$cors->add($domain);
}
$cors->send();
你明白了吧。
发布于 2011-09-27 14:07:45
您是否尝试过将Access-Control-Allow-Origin标头添加到从服务器发送的响应中?比如,Access-Control-Allow-Origin: *
https://stackoverflow.com/questions/7564832
复制相似问题