[英]JavaScript: How to get an absolute Base-URL?
I would like to avoid JavaScript in my HTML/PHP-Templates. 我想避免在我的HTML / PHP模板中使用JavaScript。 Everything is working fine as long as I don't need a base/root-URL in my external, included JS-File.
只要我在包含的外部JS文件中不需要基本/根URL,一切都可以正常工作。
Problem : Does anybody know a solution to put the JS logic (code below) into an external JS file? 问题 :是否有人知道将JS逻辑(下面的代码)放入外部JS文件的解决方案? The main problem: how to figure out the _BASE_URL_?
主要问题:如何找出_BASE_URL_? Unfortunately its not a form where you can get the URL by the action-attribute.
不幸的是,它不是一种可以通过操作属性获取URL的形式。 I dont want to compile JS/PHP-mixed files, it has to be pure JS.
我不想编译JS / PHP混合文件,它必须是纯JS。
Idea (too dirty): A hidden input in the top of the body-tag with id="root_url" or a variable in the main JS file: root_url = "http://localhost/projects/project/version/". 想法 (太脏了):在主体标签顶部的隐藏输入,其中包含id =“ root_url”或主JS文件中的变量:root_url =“ http:// localhost / projects / project / version /”。 This is prone to failure, because no file could work stand-alone.
这很容易失败,因为没有文件可以独立工作。
Maybe there's a good htaccess/mod_rewrite solution? 也许有一个很好的htaccess / mod_rewrite解决方案?
Notice : I dont want to get the hostname or the "real" root dir, because it has to work in subfolders as well! 注意 :我不想获取主机名或“真实的”根目录,因为它也必须在子文件夹中工作!
Code : 代码 :
<script type="text/javascript">
// document ready
$(function() {
// function: load items
function load_items() {
$("#items").load("<?php echo _BASE_URL_?>/items.php");
}
// load items!
load_items();
});
</script>
<!-- target div -->
<div id="items">loading</div>
Thanks in advance! 提前致谢!
Can i see your html structure 我可以看看你的HTML结构吗
function getBaseURL () {
return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
}
if you need a path also use this 如果您需要路径,请使用此
path = window.location.pathname.split( '/' );
console.log(path);
can we use like this 我们可以这样使用吗
function getBaseURL () {
return location.protocol + "//" + location.hostname + location.pathname;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.