简体   繁体   English

为什么在 Node.js 上使用 jQuery 时 $.ajax 未定义?

[英]Why is $.ajax undefined when using jQuery on Node.js?

I have a module that is supposed to run on the client, but I'm testing it on Node.js, so I'd like to make $.ajax to work.我有一个应该在客户端上运行的模块,但我正在 Node.js 上测试它,所以我想让$.ajax工作。

I installed jQuery on the project:我在项目上安装了jQuery

$ npm install jQuery

Then I'm doing this:然后我这样做:

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

$.ajax is undefined. $.ajax未定义。

It makes a bit of sense for me because ajax is static and I think the result of require("jquery") would be the equivalent of $.fn in the browser.这对我来说有点意义,因为ajax是静态的,我认为require("jquery")的结果相当于浏览器中的$.fn

How do I use $.ajax on node?如何在节点上使用$.ajax

You can find the reason from this docs: https://www.npmjs.com/package/jquery#node你可以从这个文档中找到原因: https : //www.npmjs.com/package/jquery#node

For jQuery to work in Node, a window with a document is required.要使 jQuery 在 Node 中工作,需要一个带有文档的窗口。 Since no such window exists natively in Node, one can be mocked by tools such as jsdom.由于 Node 本身不存在这样的窗口,因此可以通过 jsdom 等工具进行模拟。 This can be useful for testing purposes.这对于测试目的很有用。

But the setup code of the docs is out of date.但是文档的设置代码已过时。

The latest setup code is:最新的设置代码是:

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 = $;

Run this code, got:运行这段代码,得到:

$.get: function
$.ajax: function
normal

The normal text is the response from my local http server. normal文本是来自我本地 http 服务器的响应。

Dependencies versions:依赖版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM