node.js中的jQuery.ajax()?

时间:2011-12-26 20:09:41

标签: jquery node.js

是否可以在node.js中使用jQuery.ajax(),就像语法一样?

我正在尝试与node.js共享非UI浏览器代码。我不想用我自己的包装器替换所有现有的函数调用。

目前,当我尝试它时,它默认会说“No Transport”,因为jQuery会进行域检测。如果我通过设置jQuery.support.cors将其关闭,则会说XMLHttpRequest.open()不可用。

5 个答案:

答案 0 :(得分:40)

我能够使用XMLHttpRequest模块解决“No Transport”问题,如下所示:

var $ = require('jquery'),
    XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

$.support.cors = true;
$.ajaxSettings.xhr = function() {
    return new XMLHttpRequest();
};

答案 1 :(得分:10)

还考虑najax,它是节点请求模块的包装器,它允许服务器端请求的jquery样式语法

https://github.com/alanclarke/najax

var najax = require('najax');
najax('http://www.google.com', function(html){ console.log(html); });
najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST', success: function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){});

najax.get, najax.post, najax.put, najax.delete...

答案 2 :(得分:8)

如果您需要精确的jQuery.ajax语法,请尝试https://github.com/driverdan/node-XMLHttpRequest

但实际上,如果您可以控制调用ajax的内容,则应该使用节点http.request或类似request

的模块来执行此操作

答案 3 :(得分:7)

我也在浏览器和nodejs之间共享代码,并且还使用JQuery进行Ajax调用。 JQuery需要一个我在多米诺骨牌中使用的窗口。

更新

if (typeof module !== 'undefined' && module.exports)
{
  if (typeof global !== 'undefined' && typeof global.process !== 'undefined' &&
    Object.prototype.toString.call(global.process) === '[object process]') {
    var domino = require('domino');
    var window = domino.createWindow('<html></html>');

    var document = window.document;
    var $ = require('jquery')(window);
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    $.support.cors = true; // cross domain, Cross-origin resource sharing
    $.ajaxSettings.xhr = function() {
      return new XMLHttpRequest();
    };
  }
}

答案 4 :(得分:0)

您可以使用Electron,它允许混合浏览器和节点。

之前,我尝试在nodejs中使用canvas2d,但最后我放弃了。 nodejs默认不支持它,并且很难安装它(许多...依赖)。 在我使用Electron之前,我可以轻松使用我以前的所有browserjs代码,甚至是WebGL,并将结果值(例如结果base64图像数据)传递给nodejs代码。