简体   繁体   中英

Set ruby instance variable inside javascript function

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM