在JavaScript中发送HTTP请求以从MongoDB获取结果

时间:2011-02-16 16:38:44

标签: javascript mongodb

我在REST模式下运行MongoDB并尝试通过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
}

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

1 个答案:

答案 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请求)。他们在进行浏览时会锁定浏览器的UI,当然,他们可能需要花费一两秒钟(或十分钟)才能运行,在此期间用户体验至少可以说是令人不快的。相反,在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 :我建议您查看类似jQueryPrototypeYUIClosure或{的库{3}}。它们将平滑浏览器怪癖,简化各种事物,并添加一些有用的功能,以便您可以集中精力解决您尝试解决的实际问题,而不是担心(随机示例)Safari错误报告等问题option的默认选择值,以及Internet Explorer在事件处理程序上泄漏内存的习惯,除非你在编写代码时念诵,烧香,并定期起床和旋转三次。