【问题标题】:Why is $.ajax undefined when using jQuery on Node.js?为什么在 Node.js 上使用 jQuery 时 $.ajax 未定义?
【发布时间】:2015-05-25 07:50:37
【问题描述】:

我有一个应该在客户端上运行的模块,但我正在 Node.js 上对其进行测试,所以我想让$.ajax 工作。

我在项目上安装了jQuery

$ npm install jQuery

那我就这样做了:

var $ = require("jquery");
console.log($.ajax); // undefined

$.ajax 未定义。

这对我来说有点道理,因为ajax 是静态的,我认为require("jquery") 的结果将相当于浏览器中的$.fn

如何在节点上使用$.ajax

【问题讨论】:

  • var $ = require("jQuery"); 不是var $ = require("jquery");
  • $.ajax() 在浏览器中使用浏览器中的 XMLHttpRequest 对象进行联网。该对象在 node.js 中不存在,因此除非安装了对 $.ajax() 的某种特定于节点的支持,否则它不会存在。
  • 为什么要在节点上使用 jQuery?
  • nodejs的jquery包中没有ajax方法。 For more info

标签: javascript jquery node.js


【解决方案1】:

你可以从这个文档中找到原因:https://www.npmjs.com/package/jquery#node

要让 jQuery 在 Node 中工作,需要一个带有文档的窗口。由于 Node 中不存在这样的窗口,因此可以通过 jsdom 等工具来模拟。这对于测试目的很有用。

但是文档的设置代码已经过时了。

最新的设置代码是:

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = new JSDOM("").window;
global.document = document;

var $ = require("jquery")(window);

// test
console.log("$.get:", typeof $.get);
console.log("$.ajax:", typeof $.ajax);
$.get("http://localhost:3000", data => {
  console.log(data);
});

module.exports = $;

运行这段代码,得到:

$.get: function
$.ajax: function
normal

normal 文本是我本地 http 服务器的响应。

依赖版本:

"jsdom": "^15.2.1",
"jquery": "^3.4.1",

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多