我是node.js的新手,想要使用ajax调用进行简单的json解析,并在html页面中输出json内容。
我正在使用express csv2json转换器将csv文件转换为json,并使用bodyparser尝试解析json。
这是我的app.js文件:
//init app with express, util, body-parser, csv2json
var express = require('express');
var app = express();
var sys = require('util');
var path = require('path');
var bodyParser = require('body-parser');
var Converter = require("csvtojson").Converter;
//register body-parser to handle json from res / req
app.use( bodyParser.json() );
//register public dir to serve static files (html, css, js)
app.use( express.static( path.join(__dirname, "public") ) );
/** csv2json **/
var csvConverter=new Converter({constructResult:false, toArrayString:true});
var readStream=require("fs").createReadStream("world_data.csv");
var writeStream=require("fs").createWriteStream("outpuData.json");
readStream.pipe(csvConverter).pipe(writeStream);
console.log(writeStream);
/** handle HTTP METHODS **/
app.get('outputData.sjon', function (req, res) {
var answer = JSON.parse(req.params);
res.send( writeStream );
});
// bind server to port
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
这是我的ajax.js:
$.ajax({
type: "GET",
url: "http://localhost:3000/app.js",
async: true,
success: function(data) {
// Handle returned data
}, error: function(jqXHR, text, err) {
// Handle error if occured
}
});
这里我想在html表中输出json内容:
<table>
<thead>
<tr id="table_head">
<th>ID</th>
<th>Country</th>
<th>birth rate / 1000</th>
<th>cellphones / 100</th>
<th>children / woman</th>
<th>electric usage</th>
<th>internet usage</th>
</tr>
</thead>
<tbody id="table_body">
<!-- list countrys with ajax -->
</tbody>
</table>
json输出文件的保存方式与此数据示例类似:
{"id":"001","name":"Brazil","birth rate per 1000":"16.405","cell phones per 100":"90.01936334","children per woman":"1.862","electricity consumption per capita":"2201.808724","gdp_per_capita":"4424.758692","gdp_per_capita_growth":"-1.520402823","inflation annual":"8.228535058","internet user per 100":"39.22","life expectancy":"74","military expenditure percent of gdp":"1.615173655","gps_lat":"-14.235004000","gps_long":"-51.925280000"}
有关如何将app.js文件绑定到ajax.js并在index.html中输出json的任何信息都非常有用。感谢