我正在使用 CodeIgniter 构建一个网站,我使用 base_url 助手函数加载各种资源,如下所示:
<link rel="stylesheet" type="text/css" href="'.base_url('assets/css/themes/default.css').'" id="style_color"/>
这将生成以下内容(即 www.mysite.com):
<link rel="stylesheet" type="text/css" href="http://www.mysite.com/assets/css/themes/default.css" id="style_color"/>
然后我可以像这样在 JavaScript 中替换此资源:
$('#style_color').attr("href", "assets/css/themes/" + color_ + ".css");
问题是它将尝试加载资源而不使用 PHP 生成的绝对路径,因此我的解决方案是在每个页面中添加带有 PHP 的虚拟标签,如下所示:
<div id="base_url" class="'.base_url().'"></div>
然后我修改了 JavaScript 行:
$('#style_color').attr("href", $('#base_url').attr("class") + "assets/css/themes/" + color_ + ".css");
我更喜欢使用仅限于Javascript的解决方案。由于我正在使用CodeIgniter,因此使用
document.base_url
变量来保存从protocol
到index.php
的url段似乎很方便。
document.base_url = base_url('index.php');
其中base_url()
函数为:
function base_url(segment){
// get the segments
pathArray = window.location.pathname.split( '/' );
// find where the segment is located
indexOfSegment = pathArray.indexOf(segment);
// make base_url be the origin plus the path to the segment
return window.location.origin + pathArray.slice(0,indexOfSegment).join('/') + '/';
}
base_url
的类,你可以阅读这篇文章以了解如何在js中获取base_url
:https://dev59.com/LHM_5IYBdhLWcg3wUxnF#11775016 - Emilio Gort