admin管理员组文章数量:1278857
I am trying to set a ruby instance variable's value to the latitude and longitude values. How would you set the value of an instance variable inside a javascript function?
Something like this?
<script>
if (geoPosition.init()){ geoPosition.getCurrentPosition(geoSuccess, geoError); }
function geoSuccess(p) {
<% @lat_lng = p.coords.latidude + "," + p.coords.longitude %>
}
function geoError(){ alert("No Location: Won't be able to use Maps functionality"); }
</script>
Something is telling me I need json.
I am trying to set a ruby instance variable's value to the latitude and longitude values. How would you set the value of an instance variable inside a javascript function?
Something like this?
<script>
if (geoPosition.init()){ geoPosition.getCurrentPosition(geoSuccess, geoError); }
function geoSuccess(p) {
<% @lat_lng = p.coords.latidude + "," + p.coords.longitude %>
}
function geoError(){ alert("No Location: Won't be able to use Maps functionality"); }
</script>
Something is telling me I need json.
Share Improve this question edited Mar 25, 2013 at 3:37 sawa 168k49 gold badges286 silver badges397 bronze badges asked Mar 25, 2013 at 3:27 user2002525user2002525 431 silver badge4 bronze badges 1- 1 BTW, your code has spelled "latitude" as "latidude". – Phrogz Commented Mar 25, 2013 at 3:37
1 Answer
Reset to default 13You are not understanding where and when code runs.
Ruby (on Rails, or otherwise) runs on the server. It creates the HTML+JS+whatever that gets sent over the Internet to the client.
The client (web browser) receives this code and, among other things, executes JavaScript code.
You cannot, therefore, have your Ruby variables be set as the result of running JavaScript code…without contacting the web server again.
You need to use AJAX (or some other, lesser technology) to send a request back to the web server when that function is called.
For example (using jQuery's jQuery.post
):
function geoSuccess(p){
$.post('/newcoords',{lat:p.coords.latitude, long:p.coords.longitude});
}
and in some controller somewhere:
def newcoords
@lat_lng = [params[:lat],params[:long]].join(",")
end
本文标签: htmlSet ruby instance variable inside javascript functionStack Overflow
版权声明:本文标题:html - Set ruby instance variable inside javascript function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741252643a2366080.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论