我想使用 AJAX 将数据从 domain1.com
发布到 domain2.com
,但我的请求失败。
这是我在 domain1.com
上的代码:
$.ajax({
type: 'POST',
url: 'https://domain2.com/payment/api/server',
crossDomain: true,
data: {
Name: $("#name").val().trim(),
Email: $("#email").val().trim()
},
dataType: 'json',
success: function(data) {
alert('Success');
},
error: function (data) {
alert('POST failed.');
}
});
这是我在 domain2.com
上的服务器端代码:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com/api/': case 'http://domain1.com/api/':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name; // Just to check if I receive the value from index.php
最佳答案
您正在检查 Origin HTTP header 是否等于 'http://domain1.com/api/'
。然而,MDN CORS docs说:
The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.
您必须从字符串中删除路径,即它必须是'http://domain1.com'
。
更正server.php
代码:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name;
关于javascript - 使用 PHP、AJAX 将数据发布到不同域不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34958694/