如何使用Ajax获取QQ空间头像信息
你可以使用以下代码使用Ajax来打开URL并获取返回的数据:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=3338007395', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
// 处理返回的数据
var startIndex = response.indexOf('(') + 1;
var endIndex = response.lastIndexOf(')');
var jsonData = JSON.parse(response.substring(startIndex, endIndex));
console.log(jsonData);
}
};
xhr.send();
这段代码使用XMLHttpRequest对象打开指定的URL,并在请求状态为4(请求已完成)且状态码为200(请求成功)时处理返回的数据。首先,我们获取请求的响应文本,然后使用indexOf和lastIndexOf方法来截取出JSON数据。最后,我们将JSON数据解析为JavaScript对象,并打印到控制台上。
请注意,由于跨域安全策略,你可能无法从一个域名的页面直接访问另一个域名的资源。在这种情况下,你需要在服务器端进行跨域请求或使用代理来获取数据。
原文地址: https://www.cveoy.top/t/topic/qoE2 著作权归作者所有。请勿转载和采集!