我正在尝试通过此方式使用来自 ajax 的 Controller 操作:
var idDocumento = $(this).attr('id');
$.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "%= document_download_create_company_company_document_path(company_id:params[:id], id: %>" + idDocumento + ""<%, :format => :js ) %>",
success: function(data){
alert(data);
}
});
});
到这个 Controller :
def document_download_create
end
我需要从 ajax 调用中获取 Controller 中的参数,并在 MediaDownload 中进行插入。我已经添加了路由`document_download_create_company_company_document_path。 所以我的问题是,我应该如何获取 Controller 操作的参数,以及如何正确发送它,因为我在 :
"<%= document_download_create_company_company_document_path(company_id:params[:id], id: %>" + idDocumento + ""<%, :format => :js ) %>"
说的是
syntax error, unexpected ')'
提前致谢。
最佳答案
你的问题在这里:
<%= document_download_create_company_company_document_path(company_id:params[:id], id: %>
Erb 在执行 javascript 之前被解析。更重要的是,它完全不知道 idDocumento
代表什么——对于 erb 它只是一个文本。简而言之 - 您不能将 javascript 值传递给 erb block 。不过有一个解决办法:
var idDocumento = $(this).attr('id');
var pathTemplate = "<%=document_download_create_company_company_document_path(company_id: params[:id], id: :idDocumento, format: js) %>"
var path = pathTemplate.replace('idDocumento', idDocumento)
解释:
因为在执行 erb 时您不知道 idDocumento
,所以您用符号 :idDocumento
对它进行 stub 。这将使 erb 呈现:
var pathTemplate = "path/to/document/with/id/idDocumento/download"
因此,您的 js 需要做的就是用此时已知的值替换此 idDocumento
字符串。
关于jquery - AJAX 到 Ruby Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22338220/