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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思