如何在JavaScript中获取基本URL

78

我正在使用 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中生成基本的URL或其他解决方案。谢谢 :)
我更喜欢使用仅限于Javascript的解决方案。由于我正在使用CodeIgniter,因此使用document.base_url变量来保存从protocolindex.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(),因为我在将其传递给类名时遇到了一些问题。 - Dirgh
我不明白为什么你要添加一个带有base_url的类,你可以阅读这篇文章以了解如何在js中获取base_url:https://dev59.com/LHM_5IYBdhLWcg3wUxnF#11775016 - Emilio Gort
11个回答

225

JavaScript中的基础URL

你可以使用window.location轻松访问当前URL。

你可以通过这个locations对象访问URL的各个段。例如:

// This article:
// https://dev59.com/QmEi5IYBdhLWcg3wd8Ou

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工具中,你可以在控制台中直接输入window.location ,它将返回所有可用属性。
更多阅读请参考此Stack Overflow帖子

我对这个答案正确性并不信服。base_url是在php(服务器端)中定义的,你如何在JS/客户端中获取它? - PC.
2
@PC。“base_url”(在此示例中)只是我的变量名称。它可以是“baseURL”,“urlBase”或其他任何名称。 - chantastic

9

一种方法是使用脚本标签将您想要的变量导入到视图中:

<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>

在这里,我使用json_encode将base_url包装起来,以便自动转义任何字符为有效的Javascript。我将base_url放置在全局Window中,这样您只需调用base_url即可在任何地方使用它,但请确保将脚本标签放置在调用它的任何Javascript之上。根据您提供的示例:

...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");

6

JavaScript中的基本URL

这是一个简单的函数,可以帮助您在JavaScript项目中获取基本URL。

// base url
function base_url() {
    var pathparts = location.pathname.split('/');
    if (location.host == 'localhost') {
        var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
    }else{
        var url = location.origin; // http://stackoverflow.com
    }
    return url;
}

5
var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

5

只需对该变量进行操作即可完成此操作。

var base_url = '<?php echo base_url();?>'

现在这将有基本URL。现在制作一个JavaScript函数,它将使用此变量。
function base_url(string){
    return base_url + string;
}

现在这将始终使用正确的路径。

var path    =   "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );

4
为了得到与CodeIgniter中的base_url完全相同的内容,您可以执行以下操作:
var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';

如果您正在处理纯JavaScript文件,则此功能将更加有用。


3
您可以通过在每个页面模板中生成以下行来使PHP和JavaScript一起工作:
<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>

这样一来,您就可以在JavaScript中随时引用document.mybaseurl。这能节省您一些调试和复杂性,因为该变量始终与PHP计算保持一致。


这个在浏览器兼容性方面怎么样?有可能在某些浏览器(或旧版本的浏览器)上失败吗? - Alejandro
这段代码应该是跨浏览器的,因为差异被服务器端脚本消除了。但是这段代码可能不是“可移植”的,也就是说当你移动服务器时可能需要调整路径前缀。 - Schien

1
如果您想要网页中明确指定的内容,只需使用以下方法:
document.querySelector('head base')['href']

0

resources/views/layouts/app.blade.php 文件中

<script type="text/javascript">
    var baseUrl = '<?=url('');?>';
</script>

0
假设您有全局脚本文件,并且不想在其他文件中重复定义该URL。这就是BASE_URL发挥作用的地方。
在您的global_script.js文件中,执行以下操作:
<script>
 var BASE_URL = "http://localhost:8000";
</script>

然后您可以在任何其他地方使用该变量来调用您的URL。例如...

<script>
   fetch(`{{BASE_URL}}/task-create/`,{
         ..............
            
        }).then((response) => {
            .............
   })
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接