[英]Going from Javascript to a rails action
I currently have a city that someone 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. 我目前有一个城市,有人会进入该系统,我想从我的JavaScript操作转到Rails操作,以便可以从数据库中获取city.id。 For example
例如
my javascript 我的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. 试试ajax。 You can setup path in
routes.rb
like find_city_id_by_name?name=Washington DC
. 您可以在
routes.rb
设置路径,例如find_city_id_by_name?name=Washington DC
。 Then you can use jquery to send request. 然后,您可以使用jquery发送请求。
$.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: 在controller中,您需要编写单个ID作为请求响应:
render :text => id
More information: 更多信息:
http://api.jquery.com/jQuery.ajax/ 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. 尽管您提出的要求绝对可行,但是每次您需要按城市名称获取城市ID时查询后端对我来说都是个坏主意。 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).
如果名称本身来自后端(例如,您有可供用户选择的城市列表),则最好提供ID和名称(用户不可见,但在html中的某个位置)和ID。
You have to use AJAX to call any methods on the server-side. 您必须使用AJAX来调用服务器端的任何方法。
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. /ajax/city_id
是某些控制器中的某些操作,在您调用它时会返回JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.