[英]Rails how to update partial with json response from an ajax post request
I have an ajax post to my backend rails app, it's to post a upload a file. 我在后端Rails应用中发布了一个ajax发布信息,它发布了一个上传文件。
Post response with my files list in JSON 用JSON中的文件列表发布响应
After that I need to reload my files list at view detalhes.html.erb page. 之后,我需要在view detalhes.html.erb页面上重新加载文件列表。 This list is a partial. 此列表是局部的。 Here is what I have: 这是我所拥有的:
controller method: 控制器方法:
def upload_arquivo
@ponto_venda = PontoVenda.find(params[:pv_id])
nome = params[:key].split('/').last
@arquivo = Arquivo.new(nome: nome, endereco: params[:url], s3_key: params[:key], tamanho: params[:tam], user_id: params[:u_id], tag_id: params[:tag])
if @arquivo.save!
ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
response = { files: filtro_pv_arquivos, message: "O arquivo '#{nome}' foi salvo" }
else
response = { files: '', message: 'Ocorreu um erro ao salvar o arquivo, por favor, tente novamente' }
end
render json: response
end
My ajax post method at _arquivos_upload.html.erb
: 我在_arquivos_upload.html.erb
ajax发布方法:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
console.log(data.files.length);
// trying to reload partial after post request
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados") %>");
});
data.files are correct, I just need to find a way to pass this to my render partial. data.files是正确的,我只需要找到一种将其传递给我的渲染部分的方法。 How can I do that? 我怎样才能做到这一点? Or if this is a bad way to do it, how can I do better? 或者,如果这样做不好,我该如何做得更好?
Here is where I render my partial detalhes.html.erb
: 这是我渲染部分detalhes.html.erb
:
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados" %>
</div>
I already have try a lot of this: 我已经尝试了很多:
That looks good. 这看起来不错。 I'd suggest modifying your partial to accept a local variable and then explicitly passing it in when you render the partial. 我建议修改您的partial以接受局部变量,然后在渲染partial时显式传递它。
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados", locals { files: @files #add this } %>
</div>
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados", locals: { files : data.files } ) %>");
I think I would render back html
instead of json
. 我想我会渲染回html
而不是json
。 Then, in .success
function of the ajax
call, just do: 然后,在ajax
调用的.success
函数中,只需执行以下操作:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
$('#display-arquivos').html(data);
});
You'll probably need to change your controller action along the lines of: 您可能需要按照以下方式更改控制器操作:
def upload_arquivo
...
if @arquivo.save!
ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
@files = #populate your @files variable
render "arquivos_buscados"
else
render :something_else
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.