【问题标题】:Execute curl command using jquery-ajax使用 jquery-ajax 执行 curl 命令
【发布时间】:2013-08-11 01:17:35
【问题描述】:

我使用以下输入到 mongoDB 执行 curl 命令。

curl --data 'cmd={"geoNear" : "items", "near":[6.8590845,79.9800719]}' 'http://72.123.xxx.xxx:27080/weather/_cmd'

我想使用 jsonp 或 json 执行它并获得响应。我在 jsonp 请求下尝试过。

var url =  "http://72.123.xxx.xxx:27080/weather/_cmd";
$.getJSON(url + "?callback=?",
    {
        cmd:{"geoNear" : "items", "near": 6.8590845,79.9800719]}
    },
    function(tweets) { }
);

我没有从控制台得到任何东西。 请帮我解决一下这个。谢谢。

【问题讨论】:

标签: json jquery curl jsonp


【解决方案1】:

最后我想出了解决方案。

$.ajax({
    url: '/weather/_cmd',
    type:'POST',
    dataType: 'json',
    crossDomain : true,
    data: {
        cmd: JSON.stringify({
            "geoNear" : "items",
            "near": [6.8590845,79.9800719]
        })
    },
    success: function(res) {
        //do stuff with res
    }
});

ProxyPass /weather http://72.123.xxx.xxx:27080/weather/_cmd
ProxyPassReverse /weather http://72.123.xxx.xxx:27080/weather/_cmd

将上述代理传递添加到您的 Apache 并尝试此操作。它会起作用的。问题是您无法使用 jsonp 传递 POST 请求。 mongo 我们需要 POST 请求。这是一种方法。 :D 我对它进行了测试,并且非常适合我。它不会接受 json,您必须将其作为字符串传递。

【讨论】:

    【解决方案2】:

    您可能一无所获,因为您的 MongoDB 实例不支持 JSONP(而您需要它,因为通常您不能执行跨域 ajax 请求)或者您的查询不正确(显然您必须使用 ?jsonp= 而不是?callback=)。

    一种方法是直接使用 JSONP。由于您使用的是 jQuery,因此您可以尝试类似的方法:

    $.ajax({
        url: 'http://72.123.xxx.xxx:27080/weather/_cmd',
        dataType: 'jsonp',
        jsonp: 'jsonp', // <-- the name used in '?jsonp=' part of url
        data: {
            cmd: {
                "geoNear" : "items",
                "near": [6.8590845,79.9800719]
            }
        },
        success: function(res) {
            console.log(res);
        }
    });
    

    根据这个 StackOverflow 答案:

    Does MongoDB have a native REST interface?

    如果您使用 --jsonp 选项触发 MongoDB 实例,它应该可以工作(为了启用对 JSONP 的支持)。不过我没试过。

    还可能存在其他问题。例如,数据库可能会简单地断开连接,您可能没有权限等。通常从客户端直接连接到数据库从来都不是一个好主意。您应该使用网络服务器作为中间人。

    【讨论】:

    • 我使用你的代码,但它不起作用。 Curl 命令运行良好,它总是给我输出。请帮帮我。
    • Mongo 不接受 json 并且它作为字符串存在。主要问题来自于此。然后 jsonp 不支持 post 请求并且 mongo 只接受 post。最后我想出了解决方案。
    猜你喜欢
    • 1970-01-01
    • 2014-10-18
    • 2013-12-07
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多