cómo obtener la url base en javascript


Estoy construyendo un sitio web con CodeIgniter , tengo varios recursos que cargo con la función auxiliar base_url como esta

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

Que produce (i. e. www.mysite.com)

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

Luego puedo intercambiar este recurso con otro en javascript como este

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

Lo que sucede es que intentará cargar el recurso sin usar la ruta absoluta generada por php, por lo que mi solución fue agregar un dummy etiqueta en cada página con php como esta

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

Luego modifiqué la línea javascript a

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

Funciona, pero no se ve elegante en absoluto, por lo que agradecería cualquier ayuda sobre cómo generar esta url base desde javascript o cualquier otra solución, gracias:)


Preferí una solución solo Javascript y como estoy usando CodeIgniter , una variable document.base_url con los segmentos de la url desde el protocol hasta el index.php parecía útil

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

Con la función base_url() siendo

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('/') + '/';
}
Author: Nehemias Herrera, 2014-01-21

8 answers

URL base en JavaScript

Puede acceder a la url actual con bastante facilidad en JavaScript con window.location

Tienes acceso a los segmentos de esa URL a través de este objeto locations. Por ejemplo:

// 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"]

En Chrome Dev Tools, simplemente puede ingresar window.location en su consola y devolverá todas las propiedades disponibles.


Hay más lecturas disponibles en este hilo de desbordamiento de pila

 104
Author: chantastic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:30

Una forma es usar una etiqueta de script para importar las variables que desea a sus vistas:

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

Aquí, envolví el base_url con json_encode para que escape automáticamente cualquier carácter a Javascript válido. Puse base_url en la ventana global para que pueda usarlo en cualquier lugar simplemente llamando a base_url, pero asegúrese de poner la etiqueta de script encima de cualquier Javascript que lo llame. Con su ejemplo dado:

...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");
 8
Author: sean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-21 00:33:06

Esto se hace simplemente haciendo esta variable.

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

Esto tendrá url base ahora. Y ahora hacer un javascript función que utilizará esta variable

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

Y ahora esto siempre usará la ruta correcta.

var path    =   "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );
 4
Author: Muhammad Raheel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-21 07:07:54
var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";
 3
Author: goofballLogic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-07 13:22:16

Puede hacer que PHP y JavaScript funcionen juntos generando la siguiente línea en cada plantilla de página:

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

Entonces puede referirse al documento.mybaseurl en cualquier lugar de tu JavaScript. Esto le ahorra algo de depuración y complejidad porque esta variable siempre es consistente con el cálculo de PHP.

 2
Author: Schien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-21 00:23:46

URL base en JavaScript

Aquí está la función simple para que su proyecto obtenga la URL base en JavaScript.

// 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;
}
 0
Author: hsn0331,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 03:13:25

Puedo llegar tarde, pero para todos los geeks del Futuro. Primero supongo que quieres llamar a base_url en tu archivo .js. así que vamos a considerar que lo está llamando a continuación muestra .js archivo

Muestra.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");
}

En lo anterior no hay base_url asignado.Por lo tanto, el código no funcionará correctamente. Pero es seguro que llamarás al archivo .js entre <head></head> o <body></body>de Vista usando la etiqueta <script> </script>. Así que para llamar a base_url en el archivo.js, tenemos que escribir el siguiente código donde planea llamar al archivo .js. Y se recomienda que cree un archivo de encabezado común y coloque el siguiente código y todas las hojas de estilo de llamada (.css) y el archivo javascript (.js) allí. al igual que el siguiente ejemplo.

Archivo de cabecera común

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

Ahora el base_url también funcionará en el archivo sample.js. Espero que haya ayudado.

 0
Author: Jeeva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 10:25:10

Para obtener exactamente lo mismo que base_url de codeigniter, puedes hacer:

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

Esto será más útil si trabaja en un archivo Javascript puro.

 0
Author: Saddam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 12:08:27