【问题标题】:rails - angularjs sends http.get as html format requestrails - angularjs 发送 http.get 作为 html 格式请求
【发布时间】:2015-02-07 04:20:43
【问题描述】:

我有这段 angularjs 代码

  $http.get(sprintf("/posts/%s", post.id)).
  success(function(data, status, headers, config) {
    $scope.post = data;
  })

我希望在后端(rails)中得到一个 json 格式的请求

respond_to do |format|
  format.html
  format.json { render json: @post}
end 

但是我收到了一个 html 格式的请求。

我错过了什么?感谢您的帮助。

【问题讨论】:

    标签: javascript ruby-on-rails angularjs


    【解决方案1】:

    最简单的方法是:

    $http.get(sprintf("/posts/%s.json", post.id)).
      success(function(data, status, headers, config) {
        $scope.post = data;
      });
    

    【讨论】:

    • 谢谢,除了将 .json 添加到 url 之外,还有其他更好的方法吗?
    • 好吧,只要你的 Rails 控制器同时响应 html 和 json,你的 Angular 应用程序就需要告诉 Rails 它需要json。您可以使用$httpProvider 修改Accept 标头,或者告诉Rails 始终为带有X-Requested-With: XMLHttpRequest 的请求提供json,但我相信只输入.json 是简单且最好的。
    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2013-06-06
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多