Going from Javascript to a rails action
I currently have a city that someon开发者_如何学Pythone will enter into the system and I want to go from my javascript action to a rails action so i can get the city.id from the database. For example
my javascript
function get_city(city){
//city comes in like "Washington DC"
}
my rails action
def return_city_id
@city = City.find_by_name(params["name"])
return @city.id
end
Try ajax. You can setup path in routes.rb
like find_city_id_by_name?name=Washington DC
. Then you can use jquery to send request.
$.ajax({
url: 'find_city_id_by_name',
data: {'name' : city},
dataType: 'text',
success: function(id) {
alert(id);
}
});
In controller, you'll need to write single id as request response:
render :text => id
More information:
http://api.jquery.com/jQuery.ajax/
Although what you ask is definitely doable, querying back-end each time you need to fetch city id by its name sounds like a bad idea to me. If the name itself come from back-end (for example, you have list of cities for user to choose from), it's better to provide ids together with names (not visible to user, but somewhere in html).
You have to use AJAX to call any methods on the server-side.
function get_city(city){
$.getJSON("/ajax/city_id", { "city" : city }, function(data)
{
//Do something with data
});
}
/ajax/city_id
is some action in some controller that returns JSON when you call it.
精彩评论