我正在关注 Heroku 图片上传 tutorial其中 application.js 中包含以下代码 -
fileInput.fileupload({
fileInput: fileInput,
url: '<%= @s3_direct_post.url %>',
type: 'POST',
autoUpload: true,
formData: <%= @s3_direct_post.fields.to_json.html_safe %>,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
replaceFileInput: false
});
...你可以看到formData:
erb 周围没有引号 - 当我部署代码时,这会导致 javascript 错误 - SyntaxError: Unexpected token '<'
那个 erb 应该用引号引起来,对吗?非常感谢任何评论。
最佳答案
不要这样做 - 它可能在开发中有效,但在生产中会中断,因为默认生产配置假定所有资源都已预编译并由服务器提供服务。这显然可以更改,但可能会导致一些性能问题。
如果您需要将任何数据从 Controller 传递到 JavaScript,请使用 gon
gem:
Controller :
gon.fileUpload = {
url: @s3_direct_post.url,
data: @s3_direct_post.fields.to_json
}
然后你就可以在100%静态javascript中使用它了:
fileInput.fileupload({
fileInput: fileInput,
url: gon.fileUpload.url
type: 'POST',
autoUpload: true,
formData: gon.fileUpload.data,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
replaceFileInput: false
});
当然你需要遵循gon安装指南。
关于javascript - 在 application.js 中使用嵌入式 ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28341130/