2012-02-26 36 views
0

我正在localhost:8080上运行开发服务器,现在正在使用终端。我安装nodejs用下面的命令:使用来自nodeJS解释器的jQuery ajax

$ brew install node 
$ brew install jquery 

现在我运行node解释:

$ node 
> var $ = require("jquery"); 

我定义的函数打印出来不管它获得控制台:

function getSomething() { 
    $.get("http://localhost:8080", 
      function(response) { 
       console.log(response); 
    }); 
} 

所以在翻译:

> getSomething() 
undefined <-- this is what I get 

我认为这是由于相同的原产地政策。我如何解决这个问题?我试图练习我的JavaScript,我想在终端而不是浏览器控制台上工作,以保持它的速度。

回答

2
  1. getSomething doens't return return anything。所以undefined是默认的返回值。这是对的。
  2. 你认为ajax节点的核心API的哪一部分?是否有机会window.XMLHttpRequest。这有没有可能不存在?
  3. 你为什么要在节点上使用jQuery?是否要抽象出跨浏览器合规性问题?那是什么?他们不存在?然后不要使用jQuery
  4. 你可能不明白,GET请求必须是异步的,因此不能返回任何东西,它会在返回后记录响应
  5. 如果你想练习JavaScript,然后使用jQuery将不会帮助你

虽然严重,使HTTP请求的方式很容易

$ npm install request

var request = require("request"); 

function makeRequest(callback) { 
    request("http://localhost:8080", callback); 
} 

makeRequest(function (err, res, body) { 
    console.log(body); 
});