【问题标题】:Converting ajax to node.js将 ajax 转换为 node.js
【发布时间】:2015-01-22 04:23:31
【问题描述】:

我已经学会了处理 ajax 调用以将信息从服务器交换到浏览器,但现在我在使用 http 请求将我的代码转换为与服务器端节点兼容的 JS 时遇到了很大的麻烦。我已经阅读了不同的教程,但我无法将它们适应我的代码。 我的简单 JS/jQuery 函数是这样的:

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

我需要将它转换为带有 h​​ttp 请求的纯 JS 版本,以便与 node.js 一起使用。感谢您的帮助。

编辑:我试了又试,但没有成功。这是我使用的代码,我只是在我的console.log上得到了很多无意义的词,也许你可以纠正它:

版本 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);
    }
);

第 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);
    }
});

【问题讨论】:

标签: javascript jquery ajax node.js


【解决方案1】:

使用request.js

例子:

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.
  }
})

文档request.js

【讨论】:

  • mhh 好的,谢谢,那肯定很有用,但如果可能的话,我想避免使用库,我认为转换这个简单的函数也可能产生简单的 JS……我是如果您知道我的意思,也有兴趣“看到”执行该 http 请求的纯 JS,只是出于好奇!
猜你喜欢
  • 2015-12-30
  • 2019-03-19
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 2019-12-17
相关资源
最近更新 更多