在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。
基本路径可以是以下示例中的任意一个:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
例子也可能改变。
在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。
基本路径可以是以下示例中的任意一个:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
例子也可能改变。
当前回答
获取基本url 从js调用控制器
function getURL() {
var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && this.status==200){
//console.log(xhr.responseText); //the response of the request
document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
}
}
其他回答
我认为这对你很有用:
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );
我在几个Joomla项目中遇到过这种需求。我发现的最简单的方法是在模板中添加一个隐藏的输入字段:
<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />
当我需要的值在JavaScript:
var baseurl = document.getElementById('baseurl').value;
不像使用纯JavaScript那样花哨,但很简单,可以完成工作。
这将得到base url
var baseurl = window.location.origin+window.location.pathname;
我只是在同一个舞台上,这个解决方案对我来说很管用
在视图中
<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('var base = \''.JURI::base().'\'');
$document->addScript('components/com_name/js/filter.js');
?>
在js文件中,你将base作为一个变量访问,例如在你的场景中:
console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example
我不记得我把这个信息给信用,如果我找到它,我会编辑答案
我建议每个人在开发中创建HTML基础标签,然后动态分配href,所以在生产中,无论客户端使用什么主机,它都会自动适应它:
<html>
<title>Some page title</titile>
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var base = document.createElement("base");
base.href = window.document.location.origin;
head.appendChild(base);
</script>
</head>
...
因此,如果您在localhot:8080中,您将从基中访问每个链接或引用的文件,例如:http://localhost:8080/some/path/file.html 如果你在www.example.com,它将是http://www.example.com/some/path/file.html
还要注意的是,你所在的每个位置,你不应该在hrefs中使用像glob这样的引用,例如:父位置导致http://localhost:8080/而不是http://localhost:8080/some/path/。
假装你引用所有的超链接作为完整的句子没有bas url。