REST AJAX request to mongoDB



我正试图通过AJAX向mongoDB发送XMLHttpRequest以检索文档。

这是我的代码:

function getJsonDocumentByModeldid(model_id) {
    var valoreInput = document.getElementById('inputModelId').value;
    alert(valoreInput);
    $.ajax({
      url: "http://localhost:28017/test/",
      type: "get",
      //data: "filter_a=" + valoreInput,
      dataType: 'jsonp',
      crossDomain: true,
      success: function (data) {
        alert("success");
        //var json2javascript = $.parseJSON(data);
        manageLayout();
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
       alert("Status: " + textStatus + "    Error:" + errorThrown);
      }
  });
}

函数总是返回一个错误。那么问题是什么呢?

此功能支持作为简单(只读)REST接口的一部分,但是要使--jsonp跨域请求,否则您将受到同源策略问题的影响,因为您正在发出请求的IP地址和端口与mongoDB正在运行的IP地址和端口不匹配。

启动mongoDBmongod.exe --rest --jsonp(加上任何其他选项,你可能有)。

下面的示例页面可以通过web服务器(例如Apache HTTP服务器)提供,或者简单地保存在本地并作为文件加载到浏览器中。该请求是关于名为andyb的dbCollection的信息,我首先在mongoDB中创建了:

db.createCollection('andyb');

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>mongoDB AJAX demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
  <script type='text/javascript'>//<![CDATA[
  $(function(){
    $.ajax({
      url: 'http://localhost:28017/local/andyb',
      type: 'get',
      dataType: 'jsonp',
      jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"
      success: function (data) {
        console.log('success', data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('error', errorThrown);
      }
    });
  });//]]>
  </script>
</head>
<body>
</body>
</html>

许多浏览器现在都支持CORS,这是一种方便跨域资源的替代(更现代)方式。

前面的答案可以通过使用延迟对象来修改(参见这个很好的指南:"如何从异步调用返回响应?":

<!doctype html>
<meta charset="utf-8">
<title>mongoDB AJAX demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js" ></script>
<script>    
    $(function(){ 
    // add rest = true and jsonp = true to /etc/mongodb.conf, 
    // then restart mongodb
         $.ajax({
                url: "http://localhost:28017/local/startup_log/",
                type: 'get',
                dataType: 'jsonp',
                jsonp: 'jsonp', // mongodb is expecting that                                                                                     
            })
            .done(function(data) {
                d=JSON.stringify(data,undefined,1);
                $("code").text(d).css("color","green");
            })
            .fail(function(request,status,error) {
                $("code").text("get failed: "+error).css("color","red");
            })
            .always(function() {
                console.log("finished")
            })
  });
</script>
<body>
  <pre>
    <code>
    </code>
  </pre>

无论如何,在这两种情况下,error:fail()处理仅在没有提供端口时才有效。例如:

url:"localhost/asdasdasd"

导致错误处理;而

url:"localhost:28017/asdasdasd"

在控制台中导致404日志,如下所示:

GET http://localhost:28017/?jsonp=jQuery110207253803350031376_1383522587177&_=1383522587178 404 (OK) 

最新更新