问题描述
我正在使用 CodeIgniter 构建一个网站,我使用 base_url 这样的辅助函数
I am building a website with CodeIgniter, I have various resources that I load with the base_url helper function like this
<link rel="stylesheet" type="text/css" href="'.base_url('assets/css/themes/default.css').'" id="style_color"/>
产生(即 www.mysite.com)
which produces (i.e. www.mysite.com)
<link rel="stylesheet" type="text/css" href="http://www.mysite.com/assets/css/themes/default.css" id="style_color"/>
然后我可以像这样在javascript中将这个资源与另一个资源交换
I can then swap this resource with another in javascript like this
$('#style_color').attr("href", "assets/css/themes/" + color_ + ".css");
发生的情况是它会尝试在不使用 php 生成的绝对路径的情况下加载资源,所以我的解决方案是在每个带有 php 的页面中添加一个虚拟标签,如下所示
what happens is that it will try to load the resource without using the absolute path generated by php, so my solution was adding a dummy tag in every page with php like this
<div id="base_url" class="'.base_url().'"></div>
然后我将 javascript 行修改为
I then modified the javascript line to
$('#style_color').attr("href", $('#base_url').attr("class") + "assets/css/themes/" + color_ + ".css");
它确实有效,但它看起来一点也不优雅,所以,我很感激有关如何从 javascript 或任何其他解决方案中生成此基本 url 的任何帮助,谢谢 :)
it does work but it doesn't look elegant at all, so, I would appreciate any help on how to maybe generate this base url from within javascript or any other solution, thanks :)
我更喜欢仅使用 Javascript 的解决方案,因为我使用的是 CodeIgniter,一个 document.base_url
变量与从 protocol
到 index.php
的 url 段似乎很方便
I preferred a Javascript only solution and since I am using CodeIgniter, a document.base_url
variable with the segments of the url from the protocol
to the index.php
seemed handy
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('/') + '/';
}
推荐答案
JavaScript 中的基本 URL
您可以在 JavaScript 中使用 window.location
您可以通过这个 locations
对象访问该 URL 的片段.例如:
You have access to the segments of that URL via this locations
object. For example:
// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript
var base_url = window.location.origin;
// "http://stackoverflow.com"
var host = window.location.host;
// stackoverflow.com
var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]
在 Chrome Dev Tools 中,您只需在控制台中输入 window.location
,它就会返回所有可用的属性.
In Chrome Dev Tools, you can simply enter window.location
in your console and it will return all of the available properties.
这篇关于如何在javascript中获取基本网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!