简体   繁体   English

如何在javascript中获取基本网址

[英]how to get the base url in javascript

I am building a website with CodeIgniter , I have various resources that I load with the base_url helper function like this我正在使用CodeIgniter构建一个网站,我使用base_url辅助函数加载了各种资源,如下所示

<link rel="stylesheet" type="text/css" href="'.base_url('assets/css/themes/default.css').'" id="style_color"/>

which produces (ie www.mysite.com)产生(即 www.mysite.com)

<link rel="stylesheet" type="text/css" href="http://www.mysite.com/assets/css/themes/default.css" id="style_color"/>

I can then swap this resource with another in javascript like this然后我可以像这样用javascript中的另一个资源交换这个资源

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

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发生的情况是它会尝试在不使用 php 生成的绝对路径的情况下加载资源,所以我的解决方案是在每个带有 php 的页面中添加一个虚拟标签,如下所示

<div id="base_url" class="'.base_url().'"></div>

I then modified the javascript line to然后我将 javascript 行修改为

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

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 或任何其他解决方案中生成此基本 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我更喜欢只使用 Javascript 的解决方案,因为我使用的是CodeIgniter ,一个document.base_url变量,其中包含从protocolindex.php的 url 段似乎很方便

document.base_url = base_url('index.php');

with the function base_url() being函数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 in JavaScript JavaScript 中的基本 URL

You can access the current url quite easily in JavaScript with window.location您可以使用window.location在 JavaScript 中轻松访问当前 url

You have access to the segments of that URL via this locations object.您可以通过此locations对象访问该 URL 的段。 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"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.在 Chrome Dev Tools 中,您只需在控制台中输入window.location即可返回所有可用属性。


Further reading is available on this Stack Overflow thread可在此 Stack Overflow 线程上进一步阅读

One way is to use a script tag to import the variables you want to your views:一种方法是使用脚本标签将您想要的变量导入到您的视图中:

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

Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript.在这里,我用 json_encode 包装了 base_url,以便它会自动将任何字符转义为有效的 Javascript。 I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it.我将 base_url 放在全局窗口中,因此您可以通过调用 base_url 在任何地方使用它,但请确保将脚本标记放在调用它的任何 Javascript 之上。 With your given example:用你给出的例子:

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

Base URL in JavaScript JavaScript 中的基本 URL

Here is simple function for your project to get base URL in JavaScript.这是您的项目在 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;
}
var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

This is done simply by doing this variable.这只需通过执行此变量即可完成。

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

This will have base url now.这将现在有基本网址。 And now make a javascript function that will use this variable现在创建一个将使用此变量的 javascript 函数

function base_url(string){
    return base_url + string;
}

And now this will always use the correct path.现在这将始终使用正确的路径。

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

You can make PHP and JavaScript work together by generating the following line in each page template:您可以通过在每个页面模板中生成以下行来使 PHP 和 JavaScript 协同工作:

<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>

Then you can refer to document.mybaseurl anywhere in your JavaScript.然后您可以在 JavaScript 中的任何位置引用 document.mybaseurl。 This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.这为您节省了一些调试和复杂性,因为此变量始终与 PHP 计算一致。

To get exactly the same thing as base_url of codeigniter , you can do:要获得与codeigniter base_url完全相同的内容,您可以执行以下操作:

var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';

this will be more useful if you work on pure Javascript file.如果您处理纯 Javascript 文件,这将更有用。

I may be late but for all the Future geeks.我可能会迟到,但对于所有未来的极客来说。 Firstly i suppose you want to call base_url in your .js file.首先我想你想在你的.js文件中调用 base_url 。 so lets consider you are calling it on below sample .js file所以让我们考虑你在下面的示例.js文件中调用它

sample.js示例.js

var str = $(this).serialize(); 

jQuery.ajax({
type: "POST",
url: base_url + "index.php/sample_controller",
dataType: 'json',
data: str,
success: function(result) {
alert("Success");
}

In the above there is no base_url assigned.Therefore the code wont be working properly.上面没有分配base_url。因此代码将无法正常工作。 But it is for sure that you'll be calling the .js in between <head></head> or <body></body> of View file by using <script> </script> tag.但是可以肯定的是,您将使用<script> </script>标记在 View 文件的<head></head><body></body>之间调用.js So to call base_url in .js file, we have to write the below code where you plan to call the .js file.因此,要在.js文件中调用base_url ,我们必须编写以下代码,您计划在其中调用.js文件。 And it is recommended that you create common header file and place the below code and all the calling style sheets ( .css ) and javascript ( .js ) file there.并且建议您创建通用头文件并将以下代码和所有调用样式表( .css )和 javascript ( .js )文件放在那里。 just like below example.就像下面的例子。

common header file通用头文件

<head>

<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/js/sample.js">

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


</head>

Now the base_url will work in sample.js file as well.现在base_url也将在sample.js文件中工作。 Hope it helped.希望它有所帮助。

in resources/views/layouts/app.blade.php file资源/视图/布局/app.blade.php文件中

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

如果您想要网页中确切指定的内容,只需使用:

document.querySelector('head base')['href']

Let's say you have your global scripts file and you don't want to define that URL repeatedly in other files.假设您有全局脚本文件,并且不想在其他文件中重复定义该 URL。 That's the point where BASE_URL kicks in.这就是 BASE_URL 发挥作用的地方。

In your global_script.js file, do this在您的 global_script.js 文件中,执行以下操作

<script>
 var BASE_URL = "http://localhost:8000";
</script>

Then you can use that variable anywhere else to call your URL.然后您可以在其他任何地方使用该变量来调用您的 URL。 For example...例如...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM