简体   繁体   English

使用AJAX从Ruby on Rails服务器获取JSON内容

[英]Get JSON contents from Ruby on Rails server using AJAX

I have some experience with RoR, although, I'm kind of a newbie in AJAX matters. 我在RoR方面有一些经验,尽管我是AJAX领域的新手。 My goal is to have a HTML5 + JavaScript client and a Ruby on Rails server running in different machines (eventually). 我的目标是让HTML5 + JavaScript客户端和Ruby on Rails服务器在不同的机器上运行(最终)。

What I want is the JavaScript client to get contents from the server in JSON format, to be parsed afterwards. 我想要的是JavaScript客户端,以JSON格式从服务器获取内容,然后进行解析。 I already tried a bunch of things, like adding a "responseType", etc, but non of them worked. 我已经尝试了很多方法,例如添加“ responseType”等,但是没有一个起作用。

My current JavaScript file is like this: 我当前的JavaScript文件是这样的:

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

      alert(xmlhttp.responseText);
});

And my RoR app has a path "/contents" that calls the index function of contents_controller.rb, that is like this: 我的RoR应用程序有一个路径“ / contents”,它调用contents_controller.rb的索引函数,如下所示:

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

Is AJAX even the correct way to do this? AJAX甚至是正确的方法吗? I'm a bit lost. 我有点迷路了。

Thanks a lot! 非常感谢!

With jQuery, you can do it like this. 使用jQuery,您可以这样做。

$.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 */}
});

Your format.json shall handle your responses. 您的format.json将处理您的响应。

You can simply call /contents.json (add .json with every url to get output fron json template) or Set your default format as json if you never need html view. 您可以简单地调用/contents.json(在每个URL上添加.json以获取fron json模板的输出),或者如果您不需要html视图,则将默认格式设置为json。 For that ... 为了那个原因 ...

You can modify your routes.rb files to specify the default format. 您可以修改routes.rb文件以指定默认格式。

routes.rb routes.rb

resources :contents, defaults: {format: :json}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM