【问题标题】:Returning HTML and JSON to jquery post call in Rails在 Rails 中将 HTML 和 JSON 返回到 jquery post 调用
【发布时间】:2015-07-11 12:26:03
【问题描述】:

在我的 Rails 应用程序中,我需要将一个 html 视图返回给 Jquery post() 调用,该调用将由 java 脚本进行 到目前为止,我只返回 JSON,它是通过以下方式完成的

render json: results 

如何返回要在 JQuery 中处理的 JSON 数据和 HTML 数据? 我在哪里存储这个视图文件?

【问题讨论】:

  • 只是为了好玩,尝试rails g scaffold article title desc,然后rake db:migrate 然后rails s 然后在浏览器中localhost:3000/articles/new 创建新数据然后尝试localhost:3000/articles/1 还有localhost:3000/articles/1.json 也请注意app/controllers/articles_controller.rbapp/views/articles/show.html.erb 中的代码。
  • 你能解释一下你的有趣任务到底想做什么吗?/
  • 看看你的问题是如何得到解答的,你可以在控制器文件中看到 rails 如何处理 json 和 html 格式,还可以看到 html 文件是如何呈现的。试一试...完成后您可以删除这些文件,没什么大不了的rails d scaffold article.. 一切都消失了....

标签: javascript jquery html ruby-on-rails ruby


【解决方案1】:

您可以在控制器中使用 respond_to。然后根据 jQuery 请求发送的格式,将执行任何一个(foo.json 或只是 foo,尽管您也可以在 jQuery 中强制使用内容类型,因此请检查此)。

respond_to do |which|
  which.html # Renders the view
  which.json { render json: results }
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多