问题描述
在我的rails应用程序中,创建了一个帖子后,我有一个javascript回调,该帖子会轮询处理端点以检查图像是否已完成处理,然后像这样更新视图:
In my rails app I have a javascript callback after the a post is created that polls a processing endpoint to check if an image has finished processing and then updates the view like this:
create.js.erb 创建回调
// start polling for processed image
function imageProcessed() {
$.ajax({ url: "/posts/" + <%= @post.id %> + "/processing"})
.done(function(data) {
if (data.processing) {
setTimeout(imageProcessed(), 2000);
} else {
// append image url when processed
$("#js-capture-container").html('<img src="' + data.image_url + '" alt="image">');
}
});
}
imageProcessed();
posts_controller.rb 端点
def processing
data = { processing: @post.image_processing }
if [email protected]_processing?
data[:image_url] = @post.image_url(:pair)
end
render json: data
end
这工作正常,但是我想获取ajax中返回的数据,并使用此数据渲染已经存在的_post.html.erb部分.
This works fine, but I would like to take the data returned in the ajax and render the already existing _post.html.erb partial with this data.
类似的操作,返回更新后的@post实例,然后将该对象渲染为局部对象.
Something like return an updated instance of @post and then render that object into the partial.
<%= scape_javascript(render @post)%>"
在create.js.erb中
"<%= escape_javascript(render @post) %>"
in create.js.erb
任何想法都会大有帮助,谢谢!
Any ideas would greatly help, thanks!
推荐答案
我能够通过将部分内容呈现为json对象内部的HTML字符串来使其工作,类似于在此问题中所做的事情: rails 3-如何将PARTIAL呈现为Json响应
I was able to get it work by rendering the partial as a string of HTML inside of the json object, similar to what's being done in this question: rails 3 - How to render a PARTIAL as a Json response
我将 post_controller.rb 中的if语句更改为:
I changed the if statement in post_controller.rb to:
if [email protected]_processing?
data[:partial] = render_to_string(@post)
end
,然后在 create.js.erb 中将回调更改为:
and then in create.js.erb changed the callback to:
$("#js-capture-container").html(data.partial);
非常好,非常干净.
这篇关于Rails使用JSON对象渲染部分对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!