JavaScript 可以通过 XMLHttpRequest 对象或更现代的 fetch API 建立网络连接并从其他网站检索数据。以下是两种方法的详细说明:
方法 1:使用 XMLHttpRequest步骤创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();打开连接指定请求方法(如 GET 或 POST)和目标 URL:
xhr.open("GET", "https://example.com/data.json"
);发送请求
xhr.send();处理响应通过 onload 事件检查状态码并获取数据:
xhr.onload = function() { if (xhr.status === 200) { // 解析 JSON 响应(假设返回的是 JSON 数据) var data = JSON.parse(xhr.responseText); console.log(data); } else { console.error("请求失败,状态码:" + xhr.status); }};
完整示例var xhr = new XMLHttpRequest();xhr.open("GET", "https://example.com/data.json"
);xhr.send();xhr.onload = function() { if (xhr.status === 200) { try { var data = JSON.parse(xhr.responseText); console.log("获取的数据:", data); } catch (e) { console.error("解析 JSON 失败:", e); } } else { console.error("请求失败,状态码:" + xhr.status); }};注意事项- 跨域问题:如果目标网站未设置 CORS(跨域资源共享)头,浏览器会阻止请求。需确保目标服务器允许跨域请求(如返回 Access-Control-Allow-Origin: *)。
- 错误处理:添加 onerror 事件处理网络错误:xhr.onerror = function() { console.error("网络错误");};
方法 2:使用 Fetch API(推荐)fetch 是更现代的替代方案,语法更简洁,支持 Promise。
步骤发起请求
fetch("https://example.com/data.json"
) .then(response => { if (!response.ok) { throw new Error("请求失败,状态码:" + response.status); } return response.json(); // 直接解析 JSON }) .then(data => console.log("获取的数据:", data)) .catch(error => console.error("错误:", error));发送 POST 请求(带请求体)
fetch("https://example.com/api"
, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: "value" })}) .then(response => response.json()) .then(data => console.log(data));
优势- 更简洁的 Promise 链式调用。
- 内置 JSON 解析(response.json())。
- 更好的错误处理(通过 catch 捕获网络和解析错误)。
注意事项- 同样受跨域限制,需目标服务器支持 CORS。
- 旧版浏览器(如 IE)不支持 fetch,需引入 polyfill(如 whatwg-fetch)。
常见问题解决跨域错误
确保目标服务器配置了正确的 CORS 头。
如果是本地开发,可禁用浏览器安全策略(仅限测试):chrome.exe --disable-web-security --user-data-dir="C:/temp"
异步处理XMLHttpRequest 和 fetch 默认异步,如需同步请求(不推荐),可设置:
xhr.open("GET", "url", false); // 同步(阻塞代码)超时设置
xhr.timeout = 5000; // 5 秒超时xhr.ontimeout = function() { console.error("请求超时");};
总结- 简单请求:优先使用 fetch,代码更简洁。
- 兼容性要求高:使用 XMLHttpRequest。
- 跨域问题:需服务器支持 CORS 或使用代理。
根据需求选择合适的方法,并始终处理错误和边界情况(如网络失败、无效 JSON)。