在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
例子也可能改变。
当前回答
我只是在同一个舞台上,这个解决方案对我来说很管用
在视图中
<?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
我不记得我把这个信息给信用,如果我找到它,我会编辑答案
其他回答
这在javascript中是不可能的,因为这是一个服务器端属性。客户端上的Javascript无法知道joomla安装在哪里。最好的选择是在页面javascript中包含$this->baseurl的值,然后使用这个值(phpBaseUrl)。
然后你可以像这样构建url:
var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;
容易
$('<img src=>')[0].src
生成一个带有空src-name的img会迫使浏览器自己计算base-url,不管你是否有/index.html或其他什么。
获取基本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;
}
}
}
文档。baseURI返回的基本URL也与<base/>标签中的值有关 https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];