weixin_33739646 2013-04-11 07:44 采纳率: 0%
浏览 53

使用Express进行AJAX通话

I am trying to append HTML dynamically with Express framework in a static HTML file that my server serves. I've found about the cheerio module that does exactly what I want, but I was wondering if there is a much cheaper way for the system instead of loading the whole HTML and appending a string.

I searched about AJAX and how to communicate with the client but I didn't manage to make it work. The code I am using with cheerio is:

exports.modify = function(req, res){

  var html = fs.readFileSync(__dirname + '/../public/index.html', 'utf8'); 
  var $ = cheerio.load(html);
  var scriptNode = '<p>Source code modified</p>';
  $('body').append(scriptNode);

  fs.writeFile(__dirname + '/../public/index.html', $.html(), function (err) {
    if (err) throw err;
    console.log('It\'s modified!');
    });

  res.send($.html());

}; 

How can I do it in more 'proper' way (maybe with AJAX call)? Any suggestions would be more than welcome.

  • 写回答

1条回答

  • 程序go 2013-04-11 08:47
    关注

    Assuming you want to handle JSON as a data type then you can setup another specific route or you can filter the request type within the current route handler :

    exports.index = function(req, res) {
      var data = someData.fetch();
      switch(req.format) {
        case 'json':
          res.json(data);
          break;
        default:
          res.render('template', {
          data:data
        });
      }
    };
    
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程