如何在Node.js中使用jQuery?

3

我正在尝试在我的Node.js文件中使用jQuery。我已经安装了jQuery模块。

当我访问页面时,出现以下错误:

    var jqxhr = jquery.$.getJSON( "favs.json", function() {
                         ^
TypeError: Cannot call method 'getJSON' of undefined
    at Server.<anonymous>
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2076:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
    at Socket.socket.ondata (http.js:1966:22)
    at TCP.onread (net.js:525:27)

代码:

var http = require('http');
var jquery = require('jquery');

var PORT = 3000;

http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': "*"});

    var jqxhr = jquery.$.getJSON( "favs.json", function() {
        console.log( "success" );
    })
    .done(function() {
        console.log( "second success" );
    })
    .fail(function() {
        console.log( "error" );
    })
    .always(function() {
        console.log( "complete" );
    });
}).listen(PORT);

console.log('Server running at http://127.0.0.1:' + PORT + '/');

有人知道如何修复这个问题吗?

谢谢。

1个回答

5

更新: 对于最新版本(≥2.1.0),实例化方式已经改变,现在还需要 jsdom

var env = require('jsdom').env;
var html = '<html>...</html>';

env(html, function(err, window) {
  console.log(err);

  var $ = require('jquery')(window);
});

您没有正确实例化jQuery对象。这是正确的做法:
var jquery = require('jquery');
var $ = jquery.create();

然后你可以使用你想要的方法:
$.getJSON('/resource.json', function() {
  console.log('success');
})
  .done(function() {
    console.log('second success');
  })
  .fail(function() {
    console.log('error');
  })
  .always(function() {
    console.log('complete');
  });

2
这个不起作用。TypeError: jquery.create 不是一个函数 - corysimmons
原回答发布于2013年,不适用于最近的版本。我添加了一个更新的示例。 - hexacyanide
谢谢。我已经转向使用request/cheerio来满足我的需求了,但还是感谢你的快速回复和修复。 :) - corysimmons
4
更新后的代码不能运行。出现 TypeError: env is not a function 错误。 - Frank Kong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接