javascript/jquery中的相对url &rails 3

Relative URLs in javascript/jquery & rails 3

本文关键字:url rails 相对 jquery javascript      更新时间:2023-09-26

每条记录都有一个这样的URL:

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

http://localhost:3000/items/3/这样的页面上,链接的JavaScript文件有如下代码:

$.getJSON(document.URL+'/stuff.json');

这允许我抓取JSON文件,而不用担心记录ID号。

问题出现在如下url上:

http://localhost:3000/items/3/news
http://localhost:3000/items/3/photos

:

$.getJSON(document.URL+'/stuff.json');

将查找:

http://localhost:3000/items/3/news/stuff.json

当然,这是不存在的

对于如何解决这个问题有什么想法吗?

可以使用

$.getJSON("../stuff.json", function(data){

});

如果当前url是"http://localhost:3000/items/3/anything"

编辑:

$.getJSON(document.URL.match(/'/items'/'d+'//) + "stuff.json", function(data){

});

如果所有的url都是http://host/items/id/anything

如果这个JS是由Rails渲染的(即它不是来自资产管道的东西),那么你可以使用路由助手,像这样:

<script>$.getJSON("<%= item_news_stuff_path(3, :format => :json) %>")</script>

这将生成一个相对于根路径的资源,正确地构建路由。