<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="showajax">click!</button>
<script type="text/javascript">
var Ajax={
get: function(url, fn) {
// XMLHttpRequest对象用于在后台与服务器交换数据
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
// readyState == 4说明请求已完成
if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
// 从服务器获得数据
fn.call(this, xhr.responseText);
}
};
xhr.send();
}
};
document.getElementById("showajax").addEventListener("click",function(){
Ajax.get("http://localhost:8081/",function(t){
console.log(t);
})
});
</script>
</body>
</html>
node代码:
var http = require("http");
var data = [
{
name:"qq"
},
{
age:27
},
{
action:["run","jump","codeing"]
}
];
var server = http.createServer(function(req,rsp){
rsp.writeHead(200, {'Content-Type': 'application/json'});
rsp.end(JSON.stringify(data));
});
server.listen(8081, function() {
console.log('listening on localhost:8081');
});
附:
本地跨域处理,