Reputation: 13855
I have a URL like this for each record:
http://localhost:3000/items/3/stuff.json
http://localhost:3000/items/1/stuff.json
http://localhost:3000/items/4/stuff.json
http://localhost:3000/items/9/stuff.json
when on a page such as http://localhost:3000/items/3/
, the linked JavaScript file has code like this:
$.getJSON(document.URL+'/stuff.json');
this allows me to grab the JSON file without worrying about the record ID number.
The problem arises on a URLs such as:
http://localhost:3000/items/3/news
http://localhost:3000/items/3/photos
as this:
$.getJSON(document.URL+'/stuff.json');
will be looking for:
http://localhost:3000/items/3/news/stuff.json
which of course, does not exist.
Any ideas for how I should solve this?
Upvotes: 0
Views: 692
Reputation: 25155
You can use
$.getJSON("../stuff.json", function(data){
});
if current url is "http://localhost:3000/items/3/anything"
EDIT:
$.getJSON(document.URL.match(/\/items\/\d+\//) + "stuff.json", function(data){
});
If all the urls are of the form http://host/items/id/anything
Upvotes: 1
Reputation: 107728
If this JS is rendered at all by Rails (i.e. it's not something that comes from the Asset Pipeline) then you can use the routing helpers, like this:
<script>$.getJSON("<%= item_news_stuff_path(3, :format => :json) %>")</script>
This would generate a relative-to-root path to the resource, building the route up correctly.
Upvotes: 0