使用CORS(跨域资源共享)设置允许访问其他源代码的资源。示例如下:
在所需资源的服务器端设置CORS:
header('Access-Control-Allow-Origin: http://example.com');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: X-PINGOTHER');
在客户端JavaScript代码中设置请求头:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://otherdomain.com/some.json', true);
xhr.setRequestHeader('X-PINGOTHER', 'pingpong');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send();