如何处理部分模板渲染并以 JSON 数据传递相关 HTML 数据?

发布于 2024-11-25 09:39:39 字数 460 浏览 2 评论 0原文

我正在使用 Ruby on Rails 3.0.9 和 jQuery 1.6.2 我正在尝试实现一个 AJAX HTTP 请求,在呈现的部分模板数据中处理 JSON 数据。

我想做的是渲染部分模板(在控制器操作中执行渲染过程并使用 render_to_string RoR 方法)并将渲染的 HTML 放入该 JSON 数据中。但是,我在使用 jQuery 解析 JSON 数据时遇到了一些问题,我认为是因为在部分模板中存在 "' 字符破坏了 JSON 格式。事实上,如果我渲染“简单文本”而不​​是部分所有作品

我该如何解决这个问题?

PS:我认为此主题...

I am using Ruby on Rails 3.0.9 and jQuery 1.6.2 I am trying to implement an AJAX HTTP request handling JSON data with-in a partial template data rendered.

What I would like to make is render a partial template (performing the rendering process in a controller action and using the render_to_string RoR method, as well) and put the rendered HTML in that JSON data. However, I have some problem on parsing the JSON data with jQuery and I think because in the partial template there are " and ' characters that break the JSON format. In fact, if I render a "simple text" instead of the partial all works.

How can I solve this issue? What do you advice about?

P.S.: I think a similar issue is discussed in this topic...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑,眼淚并存 2024-12-02 09:39:39

这不完全是您正在寻找的内容,但您可以使用 js.erb 动态更新您的视图。

告诉控制器响应 js 格式:

respond_to do |format|
  format.js
end

在控制器的视图文件夹中创建 action_name.js.erb ,类似于:

# categories/show.js.erb
$("#content").html("<%= escape_javascript(render 'categories/_category') %>");

它不返回 JSON,而是返回部分的完整渲染的 HTML。如果需要渲染视图文件(名称中不带前导下划线),则需要传递 :file 选项并指定文件的扩展名。

It's not exactly what you're looking for, but you could use js.erb to update your views dynamically.

Tell the controller to respond to js format:

respond_to do |format|
  format.js
end

create action_name.js.erb in your controller's view folder similar to this:

# categories/show.js.erb
$("#content").html("<%= escape_javascript(render 'categories/_category') %>");

It doesn't return JSON, instead it returns the complete rendered HTML of your partial. If you need to render a view file (without the leading underscore in the name), you'll need to pass a :file option and specify the extension of the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文