在javascript函数中设置ruby实例变量 [英] Set ruby instance variable inside javascript function

查看:98
本文介绍了在javascript函数中设置ruby实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将ruby实例变量的值设置为纬度和经度值。
如何在JavaScript函数中设置实例变量的值?



类似这样吗?

 <脚本> 
if(geoPosition.init()){geoPosition.getCurrentPosition(geoSuccess,geoError); }

函数geoSuccess(p){
<%@lat_lng = p.coords.latidude +,+ p.coords.longitude%>
}

函数geoError(){alert(No Location:将无法使用Maps功能); }
< / script>

有些东西告诉我我需要json。



Ruby(on Rails或其他)在服务器上运行。它创建HTML + JS +无论通过Internet发送到客户端。



客户端(网络浏览器)接收此代码,并执行JavaScript代码。



因此,您不能将您的Ruby变量设置为运行JavaScript代码的结果,而无需再次联系web服务器。



您需要使用AJAX(或其他较小技术)在调用该函数时将请求发送回Web服务器。



例如(使用 jQuery jQuery.post ): b
$ b

} 

以及某处的控制器:

  def newcoords 
@lat_lng = [params [:lat],params [:long]]。join(,)
end


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

这篇关于在javascript函数中设置ruby实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆