var http = require("http");
var fs = require("fs");
var str='{"id":"123",name:"jack",arg:11111}';
function onRequest(request, response){
console.log("Request received.");
response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});//可以解决跨域的请求
//response.writeHead(200,{"Content-Type":'application/json', 'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
//response.write("Hello World 8888\n");
str=fs.readFileSync('data.txt');
response.write(str);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.port on 8888\n");
console.log("test data: "+str.toString());
其中data.txt和当前app.js文件的放到相同的目录下,data.txt中代码是json格式的数据:{"id":"123",name:"jack",arg:321,remark:"test data"}
通过node app.js的方式运行起来,然后就可以让html通过ajax访问数据了。
另外就是我创建的html文件,文件aaa.html内容如下:
<!DOCTYPE html>
<html>
<head>
<title>Node JS 实例</title>
<script src="jquery-1.4.4.min.js"></script>
<script>
/*
//可用于检查出错函数的错误内容,一般使用$.get()和$.post()函数就可以了
$.ajax({
url: "http://127.0.0.1:8888/",
type: "GET",
dataType: "binary", //因为是调用nodeJS返回的json数据,所以必须使用binary类型
error: function(XMLHttpRequest, textStatus, errorThrown){
var s1=XMLHttpRequest;
var s2=textStatus;
var s3=errorThrown;
alert("error message : "+errorThrown.toString())
},
success: function(data){
$("#feeds").html(data);
var dataObj=eval('('+data+')');//转换为json对象
$("#id").html("编号:"+dataObj.id);
$("#name").html("姓名:"+dataObj.name);
$("#arg").html("年龄:"+dataObj.arg);
$("span").html(dataObj.remark);
// alert( "Data is : " + data );
}
});
*/