在JavaScript中进行跨域请求通常有几种方法,以下是一些常用的技术:
CORS(Cross-Origin Resource Sharing):
CORS 是最常用的跨域请求方法。服务器通过在响应头中添加 Access-Control-Allow-Origin 来指定哪些源可以访问资源。客户端使用 XMLHttpRequest 或 fetch API 发起请求,浏览器自动处理CORS。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
JSONP(JSON with Padding):
JSONP 是一种老的跨域技术,通过动态创建