Javascript的框架太多了,所以有时候要学的东西也特别的多。最近写了一个玩艺,叫github-widget。他调用了两个github的两个接口。
一个接口是取用户信息的:https://api.github.com/users/username
另一个接口是取用户的项目的:https://api.github.com/users/username/repos
代码地址:https://github.com/kyo4311/github-widget
这两个api是数据源,拿到数据之后,只要将他显示在页面上就可以了。
先说说获取数据源的方案,这里主要用原生的XMLHttpRequest,jquery封装的ajax方便,vue-resource,还有node和python的方案。
原生JS使用XMLHttpRequest来取数据
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
var data = JSON.parse(request.responseText);
}
};
request.send();
jQuery取数据
$.get("example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
vue用vue-resource来取数据
this.$http.get('https://api.github.com/users/username')
.then(function(response) {
});
node 使用https.request来取数据
var options = {
host: 'api.github.com',
port: 443,
path: path,
method: 'GET',
headers: {
"Connection": "close",
"Content-Type": "text/html",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
}
};
https.request(options, (res) => {
var data = "";
res.on('data', (chunk) => {
data += chunk;
});
res.on("end", function() {
resolve(data);
});
}).on('error', (e) => {
resolve(e);
}).end();
pythone使用requests来取数据
r1 = requests.get('https://api.github.com/users/' + user)
先说说写模板的方案
-
原生JS没什么好说的,字符串拼接,不停的++++++,有点累
-
于是我们就用ES6,他的多行``是方便多了
-
可能引入js模板引擎,于是用了dot.js,写模板就方便多了。
-
可是html模板还是写在页面上,也许还不是很方便,我们就把他们独立出去,然后通过webpack打包实现
-
python里面用了flask的render_template。
-
node里面选用了ejs。
通过不同的技术来写同一个东西,从里面可能学到很多东西,这是一次很不借的经历。