简体   繁体   中英

rails, erb in javascript: how to remove it

I have created a javascript in the tag of my application.erb.html.
That manages an asynchronous upload of a file (actually using plupload, but that's not relevant to the question).
The javascript code that initializes the uploader object is the following:

$(function() {

var uploader = new plupload.Uploader(
    {
        browse_button: 'plupload_browse',
        url: <%= upload_tmp_path(:format => :json) %>'
    });

//...

}

As you can see in the url line, since i am in a erb page, i rely on <%= %> tags in order to pass the script the upload url.
Now, for modularity reasons, i want to put this script in its ad-hoc .js file.
Since i can't use <%= %> tags anymore, what is my best option to pass such a script the piece of information required?

只需将其作为自定义数据属性添加到页面上的可预测元素上,配置为Browse_button的元素似乎是可能的候选对象。

DOM

The bottom line is you're going to have to pass the data to JS through your HTML

As JS is client-side, and Rails is server-side, the only way to pass data to an independent JS script (not directly rendered by Rails) is to use either something like gon , as suggested by apneadiving , or by setting the url in a data attribute in your HTML directly:

#app/controllers/application_controller.rb
before_action :set_gon

private

def set_gon
    gon.push({
       upload_tmp_path: upload_tmp_url(:format => :json)
    })
end

#app/views/layouts/application.html.erb
<%= include_gon %>

This will allow you to call the url in your JS as follows:

#app/assets/javascripts/application.js
gon.upload_tmp_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM