使用jquery-ajax执行curl命令

时间:2013-08-09 06:19:34

标签: json jquery curl jsonp

我使用以下输入到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) { }
);

我从控制台得到了什么。 请帮我解决一下这个。感谢。

2 个答案:

答案 0 :(得分:5)

最后,我想出了解决方案。

$.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请求。我们需要POST请求。这是一种方法。 :D我测试了它并且对我来说非常适合。它不接受json,你必须把它作为字符串传递。

答案 1 :(得分:1)

你可能什么也没得到,因为你的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的支持),它应该可以工作。我没试过。

也可能存在其他问题。例如,数据库可能只是丢弃连接,您可能没有权限等。通常,直接从客户端连接到数据库永远不是一个好主意。您应该使用Web服务器作为中间人。