node+ajax获取并返回数据

先代码记录,等玩熟练了,开始解析代码。

server.js

1
2
3
4
5
6
7
8
9
10
var http = require('http');

http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain','Access-Control-Allow-Origin':'http://localhost:63342'}); //63342端口为webstorm IDE生成
response.write('nihao');
response.end();
}).listen(1337,'localhost',function(){
console.log('開始監聽。。。');
});
console.log('走起!');

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(function(){
$('.getData').live('click',function(){
$.ajax({
url:'http://localhost:1337',
type:'GET',
success:function(data){
console.log('success!!!');
console.log(data);
$('#res').html(data);
},
error:function(){
console.log('error!!!');
}
})
})

})

test.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.8.3.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<input type="submit" class="getData" />
<div id="res"></div>
</body>
</html>