我在我的服务器上有一个文件(采用json格式)somefile.json
,它定期更新选定的时间间隔。通过nodejs从客户端请求JSON数据
我有一个应用程序的NodeJS读取上request
事件的文件在端口8080上监听并把它作为response
如何获取JavaScript在HTML的请求的JSON数据和日志它安慰? (尝试,但失败了,见下文)
(原因为的console.log是让我知道它已经成功加载。)
我的应用程序的NodeJS
var http = require('http'),
fs = require('fs'),
filename = "somefile.json";
var server = http.createServer();
server.on('request', function(request, response) {
response.writeHead(200, {'Content-Type': 'application/json'})
fs.readFile(filename, "utf8", function (err, data) {
if (err) throw err;
response.write(JSON.stringify(data));
response.end();
});
});
server.listen(8080);
somefile.json使用我的本地机(OSX)上卷曲
{
"message": {
"success":"Information inserted successfully.", "update":"Information updated successfully.",
"delete":"Information deleted successfully.",
},
"Jennifer": {
"status":"Active"
}, "James": {
"status":"Active",
"age":56, "count":10,
"progress":0.0029857,
"bad":0
}
}
给我的以下内容:
$ curl -i -H "Accept: application/json" http://127.0.0.1:8080
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 19 Sep 2014 03:39:41 GMT
Connection: keep-aliveTransfer-Encoding: chunked
"{\n \"message\": {\n \"success\":\"Information inserted successfully.\",\n \"update\":\"Information updated successfully.\",\n \"delete\":\"Information deleted successfully.\",\n },\n \"Jennifer\": {\n \"status\":\"Active\"\n },\n \"James\": {\n \"status\":\"Active\",\n \"age\":56,\n \"count\":10,\n \"progress\":0.0029857,\n \"bad\":0\n }\n}\n"
我的HTML(不工作)
<html>
<head></head>
<body>
<script src="jquery-2.1.1.min.js"></script>
<script>
$(function() {
$.ajax({
url: 'http://127.0.0.1:8080',
contentType:"jsonp",
dataType: 'jsonp',
cache: false,
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
});
</script>
</body>
</html>
除去JSON.stringify – 2014-09-19 04:19:51
哎@rnrneverdies控制台现在给出“意外的标记”,而不是登出JSON对象 – altimit 2014-09-19 05:13:48
使用数据类型:JSONP跨域请求,这意味着请求到不同的域和数据类型:JSON为相同的域相同的原始请求。我建议使用dataType:'json' – 2014-09-19 05:19:58