开发者

Access ruby array in javascript

开发者 https://www.devze.com 2023-02-08 11:45 出处:网络
I want to access a Ruby array in javascript. Please tell me the method to do that. My array is holding the result of a sql query.

I want to access a Ruby array in javascript. Please tell me the method to do that. My array is holding the result of a sql query.

  @contacts = Contact.order("contacts.position ASC")

I am trying to do this....

for(var i=0; i< a; i++)
    {   
        var firstnameV = "<%=Contact.order('contacts.position ASC')[i].first_name%>";
        var lastnameV = "<%=Contact.order('contacts.position ASC')[i].last_name%>";
        var emailV = "<%=Contact.order('contacts.position ASC')[i].email%>";
        var contactV = parseInt("<%=Contact.order('contacts.position ASC')[i].contact_no%>";
        var posV = parseInt("&开发者_JS百科lt;%=Contact.order('contacts.position ASC')[i].position%>";  
        tx.executeSql('INSERT INTO contact_table (firstname, lastname, email, contact, pos)
        VALUES (firstnameV,lastnameV, emailV, contactV, posV)');
    }


Quick example of how you can render the value of Ruby variable to JavaScript. Add <%= yield :head %> to head tag in views/layouts/application.html.erb. Then in views/contacts/index.erb (or whatever view you use) add the following:

<%content_for :head do %>
<script type="text/javascript">
window.onload = function() {
    alert("First contact in database is <%=Contact.order('contacts.position ASC').first.name%>")
}
</script>
<%end%>

This will alert the first contact name from your database.


You can do this by using the

to_json

method in Ruby

or

render :json => @contacts


Ruby is server side language. JavaScript is mostly (server side also - e.g. node.js) client side. If you want to pass values from Ruby to JS, you could render that value as part of view in script tags or retrieve them via AJAX.

0

精彩评论

暂无评论...
验证码 换一张
取 消