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
Add a ment  | 

1 Answer 1

Reset to default 13

You 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