跨域Jquery JSONP POST到Rails应用程序

时间:2013-09-18 17:56:05

标签: javascript jquery ruby-on-rails jsonp

这是在扼杀我。尝试从我正在尝试编写的API中加载来自不同域的数据。当发送JSON参数作为POST它们被丢弃时,我已经读过某些特殊标题必须设置为before_filter:

  def cors_headers #set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Max-Age'] = "1728000"
    headers['Access-Control-Allow-Headers'] = 'content-type, accept'
  end

虽然没有运气。猜猜这是一个浏览器限制。

当我尝试将数据作为GET而不是POST发送时,它会被添加到URL中,如下所示:

Completed in 959ms (View: 0, DB: 2) | 200 OK [http://www.somedomain.com/connector/browse/Sport.json?callback=jQuery16105855946165975183_1379526705493&{%22filters%22:[{%22filter%22:{%22attribute%22:%22id%22,%22op
erator%22:%22%3E%22,%22value%22:%222%22}},{%22filter%22:{%22attribute%22:%22id%22,%22operator%22:%22%3C%22,%22value%22:%227523%22}}]}&_=1379526723982]

所以Rails基本上看不到我试图发送的过滤器

  Parameters: {"{\"filters\":"=>{}, "id"=>"Sport", "_"=>"1379526723982", "callback"=>"jQuery16105855946165975183_1379526705493"}

我正在玩的jquery片段是:

        $jq.ajax({url: "http://www.somedomain.com/connector/browse/" + x + ".json" + "?callback=?",
            type: "get", // tried post too
            dataType: "json", // tried jsonp too
            accepts: "json",
            data: req_data, // this is JSON.stringified already
            processData:false,
            contentType: "application/json; charset=UTF-8;",
            success: output
        });

我试图发送的样本数据是

{"filters":[{"filter":{"attribute":"id","operator":">","value":"2"}},{"filter":{"attribute":"id","operator":"<","value":"7523"}}]} 

有没有人知道如何解决这个问题?

Muchos gracias!

1 个答案:

答案 0 :(得分:-1)

基本上JS SOP阻止我们发送POST请求并读取响应,但这可以解决这个问题:

1)撰写请求数据,将其作为POST发送。不要指望收到回复。不要成功使用,而是使用完整。在请求中添加random-ish变量

2)将响应暂时存储在文件或会话变量或memcached服务器中的服务器端,使用上面提到的随机变量作为商店中的密钥。

3)发送第二个JSON AJAX调用以获取缓存对象。

使用memcached,确保缓存的响应不时被删除或过期,在我的情况下,应用程序会获得大量流量,如果没有设置为过期,它会垃圾邮件我的垃圾邮件服务器垃圾邮件。

here's some sample code