获得从红宝石JSON内容使用AJAX Rails的服务器红宝石、服务器、内容、JSON

2023-09-11 00:59:04 作者:先森、可不可以

我有RoR的一些经验,虽然,我是那种在AJAX事项新手。我的目标是有一个HTML5 + JavaScript客户端,并在不同的机器上的Ruby on Rails的服务器上运行(最终)。

I have some experience with RoR, although, I'm kind of a newbie in AJAX matters. My goal is to have a HTML5 + JavaScript client and a Ruby on Rails server running in different machines (eventually).

JavaScript客户端从JSON格式的服务器获取内容,我要的是,要在事后分析。我已经尝试了一堆东西,像加了responseType等,但无一次成功。

What I want is the JavaScript client to get contents from the server in JSON format, to be parsed afterwards. I already tried a bunch of things, like adding a "responseType", etc, but non of them worked.

我目前的JavaScript文件是这样的:

My current JavaScript file is like this:

$(document).ready(function() {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "http://localhost:3000/contents", true);
      xmlhttp.send();

      alert(xmlhttp.responseText);
});

和我的回报率的应用程序有一个路径/内容调用contents_controller.rb的指数函数,即是这样的:

And my RoR app has a path "/contents" that calls the index function of contents_controller.rb, that is like this:

def index
    @contents = Content.all.order('created_at DESC')

    respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @contents }
    end
end

时的AJAX即使这样做了正确的方法是什么?我有点失去了。

Is AJAX even the correct way to do this? I'm a bit lost.

非常感谢!

推荐答案

使用jQuery,你能做到这样。

With jQuery, you can do it like this.

$.ajax({
  url: '/contents',
  type: 'GET',
  dataType: 'json',
  beforeSend: function (xhr) {
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  },
  success: function(data){/* do something meaningful with data */},
  error: function(xhr, status, response) {/* your error callback */}
});

format.json 办理你的反应。