jQuery 对 mongoDB 的 REST AJAX 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16164604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:35:09  来源:igfitidea点击:

REST AJAX request to mongoDB

mongodbjquery

提问by ilamaiolo

I am trying to fire a XMLHttpRequestto mongoDB to retrieve a document via AJAX.

我正在尝试触发XMLHttpRequestmongoDB 以通过 AJAX 检索文档。

This is my code:

这是我的代码:

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);
      }
  });
}

My function always returns an error. So what is the problem?

我的函数总是返回错误。那么问题是什么?

采纳答案by andyb

This functionality is supported as part of the Simple (read-only) REST Interfacebut to make cross domain requests the --jsonpotherwise you will be subject to the Same origin policyproblem, since the IP address and port that you are making the request from do not match the IP address and port that mongoDB is running on.

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

Start mongoDBwith mongod.exe --rest --jsonp(plus any other options you may have).

使用(以及您可能拥有的任何其他选项)启动mongoDBmongod.exe --rest --jsonp

The following example page can be served via a web sever (for example Apache HTTP Server) or simply saved locally and loaded in the browser as a file. The request is for information about a dbCollection called andyb, which I created in mongoDB first with:

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

db.createCollection('andyb');

HTML

HTML

<!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>

Many browsers support CORSnow which is an alternative (more modern) way to facilitate cross domain resources.

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

回答by leonard vertighel

The previous answer can be modified by using deferred objects (see this good guide: "How do I return the response from an asynchronous call?):

可以通过使用延迟对象来修改先前的答案(请参阅此优秀指南:“如何从异步调用返回响应?):

<!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>

Anyway, in both situations the error:and fail()handling works only if a port is not provided. For instance:

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

url:"localhost/asdasdasd"

results in an error handling; while

导致错误处理;尽管

url:"localhost:28017/asdasdasd"

results in a 404 log in the console, like this:

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

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