简体   繁体   English

如何对JSON使用response_to?

[英]How to use respond_to for json?

I'm a bit confused: I'm writing a centralised controller as per this question and am getting a bit confused on the respond_to method works. 我有点困惑:我正在根据这个问题编写一个集中式控制器,并且对respond_to方法的工作有点困惑。

In a API::Controller I'd have something like this: 在一个API::Controller我会有这样的东西:

def index
  @post = Post.all
  render json: @posts
end

And on the js (AngularJS) side of things I'd have something like this: 而在js(AngularJS)方面,我会有这样的东西:

$http.defaults.headers.common.Authorization = 'Token token='+ $scope.user.auth_token;

$http.get('/api/posts').success(function (data) {

  $scope.posts = data;

});

That works fine on the API controller, however I want to use a shared controller: 在API控制器上可以正常工作,但是我想使用共享控制器:

def index
  @post = Post.all
  respond_to do |format|
    format.html { render layout: 'admin' }
    format.json { render json: @invoices }
  end
end

But when I try to do the an ajax call it seems the API is responding with html rather than json . 但是当我尝试执行ajax调用时,似乎API用html而不是json响应。

What am I missing? 我想念什么?

Append .json at the end of the URL you are trying to hit with. 在您尝试使用的URL的末尾附加.json This way, server will know that request is demanding data in JSON format, while the default format is HTML. 这样,服务器将知道请求正在请求JSON格式的数据,而默认格式为HTML。

If you are using jQuery to do AJAX, and want to receive data back in JSON format without appending .json at the end, you can use then use the function $.getJSON() , or can pass simply the option dataType: "json" in $.jquery() function call: 如果您使用jQuery进行AJAX,并且希望以JSON格式接收数据而没有在末尾附加.json ,则可以使用然后使用$.getJSON()函数,或者可以简单地传递dataType: "json"选项dataType: "json"$.jquery()函数调用中:

$.ajax({
    dataType: "json", // To receive data back in JSON
    url: url,
    data: data,
    success: success
});

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

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