2011-02-16 91 views
0

我在REST模式下运行MongoDB并试图通过HTTP请求从MongoDB服务器获取查询结果。以下是我写的简单代码:在JavaScript中发送HTTP请求以从MongoDB获得结果

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
    <script type="text/javascript"> 
    function httpGet(theUrl){ 
     //document.write(theUrl); 
     var xmlHttp = null; 
     xmlHttp = new XMLHttpRequest(); 
     xmlHttp.open("GET", theUrl, false); 
     xmlHttp.send(null); 
     document.getElementById("response").innerHTML=xmlHttp.responseText; 
    } 
    </script> 
    <title>Connection</title> 
</head> 
<body> 
    <button onclick="httpGet('http://127.0.0.1:28017/test/first/?limit=-1')" > 
     Click 
    </button> 
    <p id="response"> </p> 
</body> 
</html> 

但是我无法得到响应。而当我在我获得以下为响应浏览器的地址栏复制并粘贴URL:

{ 
    "offset" : 0, 
    "rows": [ 
     { "_id" : { "$oid" : "4d510086ce29000000007d5a" }, "date" : { "$date":60968917800000 } } 
    ], 

"total_rows" : 1 , 
"query" : {} , 
"millis" : 0 
} 

有人可以帮助,告诉我可能是什么问题。

回答

3

您的代码运行的页面是否也从127.0.0.1端口28017加载?如果没有,那就是你的问题,你正遇到Same Origin Policy

如果是(服务器和端口两者是相同的),我建议使用相对URL,所以你

httpGet('http://127.0.0.1:28017/test/first/?limit=-1') 

成为

httpGet('/test/first/?limit=-1') 

从根本上说,代码工作:http://jsbin.com/awose3


题外话:我最好强烈推荐不使用同步XHR调用(ajax请求)。他们在浏览器的用户界面过程中锁定了用户界面,当然他们可能需要一两秒钟(或十分钟)才能运行,在此期间,用户体验至少是不愉快的。相反,使用异步调用和onreadystatechange回调,像这样(显然,错误处理和其他复杂已经离开了):

function httpGet(theUrl){ 
    //document.write(theUrl); 
    var xmlHttp = null; 
    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("GET", theUrl, true); 
    xmlHttp.onreadystatechange = handleReadyStateChange; 
    xmlHttp.send(null); 

    function handleReadyStateChange() { 
     if (xmlHttp.readyState == 4) { 
     if (xmlHttp.status == 200) { 
      document.getElementById("response").innerHTML=xmlHttp.responseText; 
     } 
     } 
    } 
} 

Live example


题外话2:我建议看看像jQuery,Prototype,YUI,Closureany of several others这样的库。他们会平滑浏览器的怪癖,简化各种事情,并添加一些有用的功能,以便您可以专注于解决您尝试解决的实际问题,而不必担心诸如(随机示例)Safari误报的情况option的默认选定值,以及Internet Explorer在事件处理程序中泄漏内存的习惯,除非您在编写代码时吟唱,烧香并定期起身并旋转三次。

+0

谢谢你的回复。我没有完全得到你留言的第一部分。我有点困惑,但我会研究它,是的,我正在研究jQuery和YUI过去几天。如果你可以请建议我一个来源(除了雅虎开发者网络),从我可以阅读VUI的地方看,这很棒。 – 2011-02-16 17:43:49