Pergunta

Eu estou usando jQuery. Como faço para obter o caminho do URL atual e atribuí-la a uma variável?

Exemplo URL:

http://localhost/menuname.de?foo=bar&number=0
Foi útil?

Solução

Para obter o caminho, você pode usar:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

Outras dicas

No estilo jQuery puro:

$(location).attr('href');

O objecto localização também tem outras propriedades, como o hospedeiro, de hash, protocolo, e caminho.

http://www.refulz.com:8082/index.php#tab2?foo=789

Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

Isto irá funcionar apenas se você tem jQuery. Por exemplo:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>

Se precisar o hash parâmetros apresentar na URL, window.location.href pode ser uma escolha melhor.

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1

Você vai querer usar built-in window.location objeto de JavaScript .

Basta adicionar essa função em JavaScript, e ele irá retornar o caminho absoluto do caminho atual.

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

Espero que funcione para você.

window.location é um objeto em javascript. ele retorna seguintes dados

window.location.host          #returns host
window.location.hostname      #returns hostname
window.location.path          #return path
window.location.href          #returns full current url
window.location.port          #returns the port
window.location.protocol      #returns the protocol

em jQuery você pode usar

$(location).attr('host');        #returns host
$(location).attr('hostname');    #returns hostname
$(location).attr('path');        #returns path
$(location).attr('href');        #returns href
$(location).attr('port');        #returns port
$(location).attr('protocol');    #returns protocol

Esta é uma questão mais complicada do que muitos podem pensar. Vários navegadores suportam built-in JavaScript localização objetos e associado parâmetros / métodos acessíveis através window.location ou document.location. No entanto, diferentes sabores de Internet Explorer (6,7) não suportam estes métodos, da mesma forma, (window.location.href? window.location.replace() não suportado) assim que você tem para acessá-los de forma diferente por escrever código condicional todo o tempo para mão-hold Internet Explorer .

Então, se você tem jQuery disponível e carregado, você pode muito bem usar jQuery (localização), como os outros mencionados, porque ele resolve estes problemas. Se, no entanto, você está fazendo-a um exemplo, alguns redirecionamento de geolocalização do lado do cliente via JavaScript (ou seja, usando o Google Maps API e objeto Situação métodos), então você não pode querer carregar toda a biblioteca jQuery e escrever seu código condicional que verifica todas as versões do Internet Explorer / Firefox / etc.

Internet Explorer torna a codificação gato infeliz front-end, mas jQuery é um prato de leite.

Para o nome do host somente, use:

window.location.hostname

Esta será também trabalho:

var currentURL = window.location.href;

java-script fornece muitos métodos para recuperar URL atual, que é exibido na barra de endereços do navegador.

Test URL:

http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

Função:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • protocolo « Web-navegadores uso Protocolo de Internet, seguindo algumas regras para a comunicação entre aplicativos WebHosted e web Client (browser). (Http = 80 , https (SSL) = 443 , ftp = 21, etc.)

EX: Com números de porta padrão

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) «anfitrião é o nome dado a um ponto final (máquina na qual recurso vidas) na Internet. www.stackoverflow.com - DNS Endereço IP de um aplicativo (OR) localhost: 8080 - localhost

Nomes de domínio são que você se registrar com as regras e procedimentos da árvore de Domain Name System (DNS). servidores DNS de alguém que gere o seu domínio com o IP-Endereço para fins de endereçamento. Na hierarquia de servidores DNS o nome de raiz de um stackoverlfow.com é com.

gTLDs      - com « stackoverflow (OR) in « co « google

Sistema local você tem que manter de domínio que não são públicas em arquivos de host. localhost.yash.com « localhsot - subdomain( web-server ), yash.com - maindomain( Proxy-Server ). myLocalApplication.com 172.89.23.777

  • (/) «O caminho dá informações sobre o recurso específico dentro do hospedeiro que o cliente Web quer acesso
  • (?) «Uma consulta opcional é passar uma seqüência de pares atributo-valor separados por um delimitador (&).
  • (#) «Um fragmento opcional é muitas vezes um atributo id de um elemento específico e navegadores irá rolar este elemento em vista.

Se o parâmetro tem um Epoch ?date=1467708674 então usar.

var epochDate = 1467708674; var date = new Date( epochDate );

enter descrição da imagem aqui


Autenticação url com nome de usuário: senha, se usernaem / senha contém símbolo @
como:

Username = `my_email@gmail`
Password = `Yash@777`

Em seguida, você precisa URL codificar o @ como %40 . Consulte ...

http://my_email%40gmail.com:Yash%40777@www.my_site.com

encodeURI() (vs) < a href = "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel = "nofollow noreferrer"> encodeURIComponent() exemplo

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/

Você pode entrar window.location e veja todas as opções, para apenas o uso URL:

window.location.origin

para todo o uso caminho:

window.location.href

Há também a localização. _ _

.host
.hostname
.protocol
.pathname

Isso irá retornar o absoluto URL da página atual usando JavaScript / jQuery .

  • document.URL

  • $("*").context.baseURI

  • location.href

Se houver alguém que quer concatenar a tag URL e haxixe, combinar duas funções:

var pathname = window.location.pathname + document.location.hash;

Eu tenho isso para retirar as variáveis ??GET.

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;

Você pode simplesmente obter o seu caminho usando js si, window.location ou location lhe dará o objeto de URL atual

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);

 var currenturl = jQuery(location).attr('href');

Para obter o URL da janela pai de dentro de um iframe:

$(window.parent.location).attr('href');

NB: só funciona em mesmo domínio

Aqui está um exemplo para obter a URL atual usando jQuery e JavaScript:

$(document).ready(function() {

    //jQuery
    $(location).attr('href');

    //Pure JavaScript
    var pathname = window.location.pathname;

    // To show it in an alert window
    alert(window.location);
});


$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
    //alert(json.message);
});

A seguir são exemplos de trechos de código úteis que podem ser usados ??- alguns dos exemplos usam funções JavaScript padrão e não são específicos para jQuery:

Veja 8 Útil jQuery Snippets Para URL é & Querystrings .

Use window.location.href . Isto lhe dará a completa URL .

window.location lhe dará a atual URL , e você pode extrair o que quiser com ele ...

Se você quiser obter o caminho do site raiz, use o seguinte:

$(location).attr('href').replace($(location).attr('pathname'),'');

purl.js . Isso realmente vai ajudar e também pode ser utilizado, dependendo jQuery. Usá-lo como este:

$.url().param("yourparam");

var path = location.pathname retorna o caminho da URL atual (jQuery não é necessário). O uso de window.location é opcional.

Muito Comumente top usado 3 queridos estão

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

Todos os navegadores suportam objeto de janela Javascript. Ele define a janela do navegador.

Os objetos e funções globais tornam-se parte do objeto da janela automaticamente.

Todas as variáveis ??globais são a janela objetos propriedades e todas as funções globais são seus métodos.

O documento HTML inteiro é uma propriedade da janela também.

Assim você pode usar objeto window.location para obter atributos relacionados todos os URL.

Javascript

console.log(window.location.host);     //returns host
console.log(window.location.hostname);    //returns hostname
console.log(window.location.pathname);         //return path
console.log(window.location.href);       //returns full current url
console.log(window.location.port);         //returns the port
console.log(window.location.protocol)     //returns the protocol

JQuery

console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname')); 
console.log("href = "+$(location).attr('href'));   
console.log("port = "+$(location).attr('port'));   
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);

Em jstl podemos acessar caminho url atual usando pageContext.request.contextPath, Se você quiser fazer uma chamada ajax,

  url = "${pageContext.request.contextPath}" + "/controller/path"

Ex: na página http://stackoverflow.com/questions/406192 Isto dará http://stackoverflow.com/controller/path

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top