weixin_33721344 2015-01-18 17:03 采纳率: 0%
浏览 65

将ajax转换为node.js

I've learnt dealing with ajax calls to exchange information from the server to the browser but now I'm having big troubles converting my code to a server-side node compatible JS using http requests. I've read different tutorials but I just can't adapt them to my code. My simple JS / jQuery function is this:

function ajaxCall(data, php, callback) {
    ax = $.ajax({
        type: "POST",
        data: data,
        url: php,
        success: function (raw_data) {
            f = $.parseJSON(raw_data);
            callback(f);
        },
    });
}

And I need to convert it to a pure JS version with http requests to use with node.js. Thanks for any help.

EDIT: I tried and tried, but without success. Here is the code I used, I just get lots of meaningless words on my console.log, perhaps you can correct it:

Version 1

var data = {"action": "update", "tN": 2155};
var request = require("request");

request.post({
    url: 'http://example.com/PHP.php',
    data: data,
    }, function(error, response, body){
    console.log(body);
    }
);

Version 2

var request = require("request");
var options = {
    method: 'POST',
    uri: 'http://example.com/PHP.php',
    data: {"action": "update", "tN": 2155},
};    
request(options, function(error, response, body) {
    if(error){
        console.log(error);
    }else{
        console.log(response);
    }
});
  • 写回答

1条回答 默认 最新

  • lrony* 2015-01-18 17:10
    关注

    Use request.js

    Example:

    var request = require('request');
    request('http://www.google.com', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
      }
    })
    

    Documentation request.js

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器