Pobierz aktualny adres URL z jQuery?

Używam jQuery. Jak uzyskać ścieżkę bieżącego adresu URL i przypisać go do zmiennej?

Przykładowy URL:

http://localhost/menuname.de?foo=bar&number=0
Author: Kamil Kiełczewski, 2009-01-02

30 answers

Aby uzyskać ścieżkę, możesz użyć:

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)
 2632
Author: Ryan Doherty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-03 23:33:45

W czystym stylu jQuery:

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

Obiekt location ma również inne właściwości, takie jak host, hash, protokół i nazwa ścieżki.

 824
Author: Boris Guéry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 12:29:07
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>');

To zadziała tylko wtedy, gdy masz jQuery. Na przykład:

<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>
 488
Author: rizon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-02 21:09:26

Jeśli potrzebujesz parametrów hash obecnych w adresie URL, window.location.href może być lepszym wyborem.

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1
 75
Author: jlfenaux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-17 08:03:31

Będziesz chciał użyć wbudowanego JavaScript window.location obiekt.

 54
Author: clawr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-03 15:32:57

Wystarczy dodać tę funkcję w JavaScript, a zwróci ona bezwzględną ścieżkę bieżącej ścieżki.

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));
}
Mam nadzieję, że ci się uda.
 46
Author: Neville Bonavia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-26 20:11:00

Okno.lokalizacja jest obiektem w javascript. zwraca następujące dane

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

W jquery możesz użyć

$(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
 41
Author: Wagh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-04 05:34:07

Jest to bardziej skomplikowana kwestia, niż wielu może myśleć. Kilka przeglądarek obsługuje wbudowane Obiekty lokalizacji JavaScript i powiązane parametry / metody dostępne przez window.location LUB document.location. Jednak różne wersje programu Internet Explorer (6,7) nie obsługują tych metod w ten sam sposób, (window.location.href? window.location.replace() nie obsługiwane), więc musisz uzyskać do nich dostęp inaczej, pisząc kod warunkowy cały czas, aby trzymać Internet Explorer.

Więc jeśli masz jQuery dostępne i załadowane, możesz równie dobrze można użyć jQuery (lokalizacja), jak inni wspomniali, ponieważ rozwiązuje te problemy. Jeśli jednak wykonujesz-na przykład-jakieś przekierowanie geolokalizacyjne po stronie klienta za pomocą JavaScript( czyli za pomocą Google Maps API i metod obiektu lokalizacji), możesz nie chcieć załadować całej biblioteki jQuery i napisać kodu warunkowego, który sprawdza każdą wersję Internet Explorera / Firefoksa / itp.

Internet Explorer sprawia, że kodowanie front-end jest nieszczęśliwe, ale jQuery jest płytą z mleko.

 31
Author: negutron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-03 15:30:22

Tylko dla nazwy hosta, użyj:

window.location.hostname
 29
Author: Mahmoud Farahat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 12:28:27

Java-script zapewnia wiele metod pobierania bieżącego adresu URL, który jest wyświetlany w pasku adresu przeglądarki.

Testowy 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);

Funkcja:

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();
}
  • protocol " przeglądarki internetowe używają protokołu internetowego poprzez przestrzeganie pewnych reguł komunikacji między aplikacjami hostowanymi przez Web a klientem(przeglądarką). (http = 80, https (SSL) = 443, ftp = 21, itd.)

EX: z domyślnym portem liczby

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) " Host to nazwa nadana punktowi końcowemu (maszynie, na której żyje zasób) w Internecie. www.stackoverflow.com - DNS adres IP aplikacji (lub) localhost:8080-localhost

Nazwy domen są rejestrowane zgodnie z zasadami i procedurami drzewa Domain Name System(DNS). Serwery DNS kogoś, kto zarządza twoją domeną z adresem IP do celów adresowania. W hierarchii serwerów DNS the Root name of an stackoverlfow.com is com.

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

Lokalny system musisz utrzymywać domeny, które nie są publiczne w plikach hosta. localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

    [28]} (/) " ścieżka podaje informacje o konkretnym zasobie w hoście, do którego klient sieci Web chce uzyskać dostęp]}
  • (?) "Opcjonalnym zapytaniem jest przekazanie sekwencji par atrybut-wartość oddzielonych ogranicznikiem ( & ).
  • (#) " opcjonalny fragment jest często atrybutem id określonego element, a przeglądarki internetowe przewijają ten element do widoku.

Jeśli parametr ma epokę ?date=1467708674 następnie użyj.

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

URL Tutaj wpisz opis obrazka


Uwierzytelnianie url z username: password, Jeśli usernaem / password zawiera symbol @
jak:

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

Następnie musisz zakodować URL @ jako %40. Zobacz...

http://my_email%40gmail.com:Yash%[email protected]_site.com

encodeURI() (vs) encodeURIComponent() przykład

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 (-_.!~*')
*/
 25
Author: Yash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-03 13:31:43

To również zadziała:

var currentURL = window.location.href;
 24
Author: Suresh Pattu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 12:24:59

Możesz zalogować okno.lokalizacja i zobacz wszystkie opcje, tylko dla użycia adresu URL:

window.location.origin

Dla całej ścieżki użyj:

window.location.href
Jest też lokalizacja.__
.host
.hostname
.protocol
.pathname
 20
Author: dacopenhagen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-28 23:11:38

Zwróci absolutny URL bieżącej strony przy użyciu JavaScript/jQuery .

  • document.URL

  • $("*").context.baseURI

  • location.href

 16
Author: Riyaz Hameed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-14 15:36:35

Mam to, aby usunąć zmienne GET.

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
 13
Author: Aram Kocharyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-25 11:35:19

Jeśli jest ktoś, kto chce połączyć adres URL i tag hash, połącz dwie funkcje:

var pathname = window.location.pathname + document.location.hash;
 13
Author: Nis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 12:27:52

Możesz po prostu uzyskać ścieżkę używając samego js, window.location lub location poda ci obiekt bieżącego adresu URL

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
 13
Author: Mohideen bin Mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-27 09:42:01
 var currenturl = jQuery(location).attr('href');
 12
Author: hari maliya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-19 07:00:53

Aby pobrać adres URL okna nadrzędnego z ramki iframe:

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

NB: działa tylko na tej samej domenie

 11
Author: Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-21 19:20:09

Poniżej znajdują się przykłady użytecznych fragmentów kodu, które mogą być użyte – niektóre z przykładów wykorzystują standardowe funkcje JavaScript i nie są specyficzne dla jQuery:

Zobacz 8 przydatne fragmenty jQuery dla & Querystrings URL.

 11
Author: Issamovitch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-03 12:26:09

Oto przykład, aby uzyskać bieżący adres URL za pomocą jQuery i 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);
});
 11
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-13 19:17:35

Użyj okna .miejsce.href . W ten sposób otrzymasz pełny adres URL .

 10
Author: Saikumar Anireddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-13 19:18:17

okno.położenie poda ci aktualny adres URL i możesz wyodrębnić z niego co chcesz...

 9
Author: ZMR BINU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-13 19:12:19

Jeśli chcesz uzyskać ścieżkę do strony głównej, użyj tego:

$(location).attr('href').replace($(location).attr('pathname'),'');
 9
Author: vikas mehta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-13 19:12:54

Zobacz purl.js . To naprawdę pomoże i może być również używane, w zależności od jQuery. Użyj go tak:

$.url().param("yourparam");
 9
Author: Chuanshi Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-18 19:48:15

var path = location.pathname zwraca ścieżkę bieżącego adresu URL(jQuery nie jest potrzebne). Użycie window.location jest opcjonalne.

 9
Author: Jonathan Lin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-21 04:06:25

Wszystkie przeglądarki obsługują obiekt okna Javascript. Definiuje okno przeglądarki.

Globalne obiekty i funkcje stają się automatycznie częścią obiektu window.

Wszystkie zmienne globalne są właściwościami obiektów okien, a wszystkie funkcje globalne są jego metodami.

Cały dokument HTML jest również właściwością okna.

Więc możesz użyć okna.obiekt lokalizacja, aby uzyskać wszystkie url związane atrybuty.

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>
 9
Author: Sumesh TG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-11 09:20:58

Bardzo często używane top 3 to

1. window.location.hostname 
2. window.location.href
3. window.location.pathname
 8
Author: Nitish Kumar Pal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-08 05:09:36
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
 7
Author: Hema Ganapathy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-13 14:05:54
// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);
 5
Author: Ayan Chakraborty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 08:15:41

W jstl możemy uzyskać dostęp do bieżącej ścieżki url za pomocą pageContext.request.contextPath, Jeśli chcesz wykonać wywołanie ajax,

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

Ex: na stronie http://stackoverflow.com/questions/406192 to da http://stackoverflow.com/controller/path

 4
Author: Maleen Abewardana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 15:12:39