在我的文件views / posts / new.html.erb中,我在底部有一个脚本:
$('div #mainPhotoDropzone').dropzone({
url: "/photos?post_id=" + $("#post_form").data('post-id'),
complete: function(file){
var url = "<%= @post.photos.first.file.path %>";
$.get(url, function(data){
$('#mainPhotoDropzone').attr('style', "background-image: url('" + data.main_photo + "')");
})
}
我在页面加载时收到错误,因为@post.photos.first
尚未存在。这应该在上传完成时触发,所以当文件存在时。
如何避免此错误?当我在&#34;完成&#34;上定义它时,我不明白为什么这会在页面加载时执行。事件,我没有看到替代方案。
答案 0 :(得分:2)
{j}发送到客户端之前执行<% ... %>
内的代码。生成javascript,<%= %>
标记将替换为运行其中的代码的结果。所以如果你有例如:
I am <%= "super "*5 %>awesome.
浏览器看到的是:
I am super super super super super awesome
因为代码"super "*5
已经已经运行。