将响应解析为跨域AJAX调用的JSON对象,需要使用以下步骤:
以下是一个示例代码:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// 处理响应数据
}
};
xhr.send();
在这个示例中,我们使用XMLHttpRequest对象发送了一个GET请求到"https://example.com/api",并设置了请求头的Content-Type为"application/json"。当请求完成并且状态码为200时,我们将响应数据解析为JSON对象,并可以在回调函数中进行进一步处理。
领取专属 10元无门槛券
手把手带您无忧上云