Where do i put this jQuery in a rails application
I have this chunk on jQuery and currently its living in my index.html.erb and it works well. I have alot of snippets like this that i want to move out of the views and into some other file or files to clean them up. Here is my snippet
$("#request_artist").autocomplete({
source: function(req, add){
开发者_如何学运维$.getJSON('<%= ajax_path("artistName") %>', req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
},
});
The problem is that is the getJson call above i use a rails helper to give me the path to the location and when i add this code to application.js it fails because it doesnt know what it is. So my question would be is there a place to put this code and clean up my index.html.erb
In your index.html.rb:
<script type="text/javascript">
var artistNameUrl = '<%= ajax_path("artistName") %>';
</script>
And in a separate js file:
$('#request_artist').autocomplete({
source: function(req, add) {
$.getJSON(artistNameUrl, req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
}
});
What i do to solve your snippet:
$("#request_artist").autocomplete({
source: function(req, add){
$.getJSON('<%= ajax_path("artistName") %>', req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
},
});
I would make sure that the item, with id request_artist
also has a attribute data-url
set correctly to ajax_path("artist_name")
. You make sure that this attribute is filled in correctly in the view.
Inside your javascript no more ruby is needed, it can just use the setting of attribute data-url
.
var url = $(this).attr('data-url');
I am not quite sure how to integrate that into the autocompleter code. But i am guessing that this would work:
$("#request_artist").autocomplete({
source: function(req, add){
$.getJSON($(this).attr('data-url'), req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
},
});
精彩评论