2015-04-05 57 views
0

对于下面的示例:在节点上开始jquery,如何解决这个问题?

var $ = require('jquery'); 
$.ajax({url : 'https://api.github.com/orgs/foo/members'}) 
    .then(function(members) { 
     for (var i in members) { 
      $.ajax({url : 'https://api.github.com/users/' + members[i].login}) 
       .then(function(member) { 
        console.log(member.name) 
       }); 
     } 
    }); 

我得到这个

$.ajax({url : 'https://api.github.com/orgs/foo/members'}) 
^
TypeError: undefined is not a function 
    at Object.<anonymous> (sample.js:2:3) 
    at Module._compile (module.js:460:26) 
    at Object.Module._extensions..js (module.js:478:10) 
    at Module.load (module.js:355:32) 
    at Function.Module._load (module.## Heading ##js:310:12) 
    at Function.Module.runMain (module.js:501:10) 
    at startup (node.js:129:16) 
    at node.js:814:3 

不知道如何解决。任何帮助?

Notice that code in this answer is not helping me.我得到相同的 错误或像TypeError: Cannot set property 'cors' of undefined的东西。

1 - 我不希望为什么我使用jQuery与节点的建议。我有一个原因,我在Vim编码,想要轻松地测试代码,这些代码将与我在BROWSER中放置的代码几乎相同。如果您可以为这种节点的使用提供一个教程链接,我会很高兴(我之前在一些远程时间完成了这个任务,包括节点和Rhino)。

回答

1

我使用jsdom(不记得我以前用过):

  • npm install jsdom
  • npm install xmlhttprequest

var jsdom = require("jsdom"); 

jsdom.env("", ["http://code.jquery.com/jquery.min.js"], function(err, window) { 
    var $ = window.$ 
    $.support.cors = true; 
    $.ajax({url : 'https://api.github.com/orgs/foo/members'}) 
     .then(function(members) { 
      for (var i in members) { 
       $.ajax({url : 'https://api.github.com/users/' + members[i].login}) 
        .then(function(member){ 
         console.log(member.name) 
        }); 
      } 
     }); 
}); 
0

Ajax是浏览器发出的HTTP请求。节点不在浏览器中运行JavaScript。您希望使用Node的http库来发出HTTP请求。

如果您觉得您必须使用jQuery的.ajax()功能,那么this might help you

+0

我已经挂在问题已经 – 2015-04-05 03:18:30

+1

对不起,''.ajax()'是为了做AJAX请求。节点不在浏览器中运行,因此它需要发出正常的HTTP请求,而不是AJAX请求。问题不是'$ .ajax()'是不好的做法。问题是你没有提出AJAX请求。 – Wio 2015-04-05 03:21:08

+1

只有为了模拟浏览器环境而设置模块/库时,无所谓。 – 2015-04-05 03:22:13