简体   繁体   中英

How to call Ruby method on server from JavaScript

This seems really simple but I can't find a straightforward answer to this problem anywhere. Basically, I have a JavaScript application that is sitting on a server and it needs to pass information back and forth between the JS application and the server, which is built on Rails. First, the JS application needs to tell the server to execute a function that generates said values, and then it needs a way to get them back to the JS application so it can use them, and they communicate back and forth like this during any given session of the application.

Is there any easy way to do this? I realize Ajax is somehow involved but I can't figure out how.

You are right that the answer lies in ajax. Assuming you're using jQuery, you will need to submit a request to the server like so:

                $.ajax({ 
                    type: "GET", 
                    url: '/get_info_action',  
                    data: {some_data: some_value}, 
                    dataType: "script" 
                });

Make sure the value you choose for url is set up in your routes.rb file. There is a good Railscast about this sort of thing that helped me a lot when learning how to do this: http://railscasts.com/episodes/136-jquery-ajax-revised

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