weixin

JavaScript 获取 JSON

日期: January 8, 2019 作者:网站维护

需要在 nodejs 下运行,因为浏览器有不能跨域的安全限制,不能请求其他域名下的资源。使用XMLHttpRequest对象的open方法发起get请求,获得返回的数据,用JSON对象的parse方法解码。nodejs下没有XMLHttpRequest对象,需要先安装一个xmlHttpRequest的包,以下代码功能是获取一条微博。

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://m.weibo.cn/api/container/getIndex?type=uid&value=1668277257&containerid=1076031668277257', true);
xhr.send(null);
xhr.onload = function(){
    var wb = xhr.responseText;
    var wbo = JSON.parse(wb);
    console.log(wbo.data.cards[0].mblog.text);
}

广告内容为平台自动生成