在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。

基本路径可以是以下示例中的任意一个:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

例子也可能改变。


当前回答

拆分并加入URL:

const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))

其他回答

有同样的问题前一段时间,我的问题是,我只是需要基础url。这里有很多详细的选项,但要解决这个问题,只需使用窗口。位置的对象。实际上,在浏览器控制台中输入这个,然后按enter键选择你的选项。我的情况很简单:

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

但你不能说CodeIgniter(或php joomla)的baseurl()将返回相同的值,因为可以更改这些框架的.htaccess文件中的baseurl。

例如:

如果你在本地主机上有一个。htaccess文件:

RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

$this->baseurl()将返回http://localhost/CodeIgniter/

获取基本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 getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

我只是在同一个舞台上,这个解决方案对我来说很管用

在视图中

<?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

我不记得我把这个信息给信用,如果我找到它,我会编辑答案