简体   繁体   中英

Rails 5: Get current URL and send back to backend

So I understand in order to get the full URL on the browser you need javascript something like:

var url = window.location.href;

This by default will get the compelete URL like:

http://localhost:3000/contacts/#reference
http://localhost:3000/contacts/item

If I place the above javascript code on my application.js file, how am I going to call it on my server side like for instance on my /helpers/application_helper.rb file?

Also do I need to put my javascript into a function in order to get access with it?

Please help!

EDIT:

request.fullpath or request.orginal_url won't work on special anchor character such as http://localhost:3000/contacts/#reference that's the reason why I am asking how can I pass the js to server side.

To get current URL in /helpers/application_helper.rb You need to write the rails code like:

def get_current_url
  request.original_url
end

If you're curious about more details, check the documentation original_url

If you want value from js

In application.js

function get_url {
 var url = window.location.href;
}

In application_helper.rb

def get_full_url_helper
 javascript_tag(
     "get_url()\";"
 )
end

Are you running a full-stack rails application using .erb for the views? Need some more info....because generally in rails your back end will know what URL your at? you need to go through the router to get there. unless your making some sought of api call to rails from a client server?

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