Frage

Ich bin mit jQuery. Wie kann ich den Pfad der aktuellen URL erhalten und es zu einer Variablen zuweisen?

Beispiel URL:

http://localhost/menuname.de?foo=bar&number=0
War es hilfreich?

Lösung

Um den Pfad zu erhalten, können Sie verwenden:

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)

Andere Tipps

In der reinen jQuery-Stil:

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

Die Lage Objekt hat auch andere Eigenschaften, wie Host, Hash, das Protokoll und Pfadname.

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

Dies funktioniert nur, wenn Sie jQuery haben. Zum Beispiel:

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

Wenn Sie die Hash-Parameter in der URL benötigen, window.location.href kann eine bessere Wahl sein.

window.location.pathname
=> /search

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

Sie werden verwenden möchten JavaScript eingebauten in window.location Objekt .

Fügen Sie einfach diese Funktion in JavaScript, und es wird den absoluten Pfad des Strompfads zurück.

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

Ich hoffe, dass es für Sie arbeitet.

window.location ist ein Objekt in Javascript. es gibt folgende Daten

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

in jquery können Sie

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

Dies ist eine komplizierte Frage, als viele denken. Mehrere Browser unterstützen window.location oder document.location integrierten JavaScript-Standort Objekte und die zugehörigen Parameter / Methoden zugänglich durch. Jedoch verschiedene Varianten von Internet Explorer (6,7) diese Methoden nicht in der gleichen Art und Weise unterstützen, (window.location.href? window.location.replace() nicht unterstützt), so muss man sich anders zugreifen bedingte Codes schreiben die ganze Zeit Internet Explorer von Hand halten, .

Also, wenn Sie jQuery verfügbar und geladen haben, können Sie auch nutzen jQuery (Standort), wie die anderen erwähnt, weil es diese Probleme löst. Wenn Sie jedoch tun-als Beispiel-Clientseitige Geolocation-Umleitung via JavaScript (das heißt, mit Google Maps API und Standortobjektmethoden), dann möchten Sie möglicherweise nicht die gesamte jQuery-Bibliothek und schreiben Sie Ihre bedingten Code laden, prüft jede Version von Internet Explorer / Firefox / etc.

Internet Explorer macht die Front-End-Codierung Katze unglücklich, aber jQuery ist eine Platte aus Milch.

Für die Hostnamen nur verwenden:

window.location.hostname

Dies wird auch funktionieren:

var currentURL = window.location.href;

java-script viele Methoden liefert aktuelle URL abzurufen, die in Browser-Adressleiste angezeigt wird.

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

Funktion:

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();
}
  • Protokoll « Web-Browser zwischen auf gehosteten Anwendungen für die Kommunikation, indem Sie einige Regeln Internet Protocol und Web Client (Browser). (Http = 80 , https (SSL) = 443 , ftp = 21, etc.)

EX: Mit Standard-Portnummern

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) «Host ist der Name zu einem Endpunkt gegeben (Maschine, auf der Ressourcen-Leben) im Internet. www.stackoverflow.com - DNS IP-Adresse einer Anwendung (OR) localhost: 8080 - localhost

Domain-Namen sind, die Sie durch die Regeln und Verfahren des Domain Name System (DNS) Baum registrieren. DNS-Server von jemandem, der für die Adressierung Ihrer Domain mit IP-Adresse verwaltet. In DNS-Server-Hierarchie der Root-Name eines stackoverlfow.com ist com.

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

Lokales System müssen Sie Domäne beizubehalten, die nicht öffentlich in Host-Dateien sind. localhost.yash.com « localhsot - subdomain( web-server ), yash.com - maindomain( Proxy-Server ). myLocalApplication.com 172.89.23.777

  • (/) «Der Pfad gibt Informationen über die spezifische Ressource innerhalb des Wirtes, dass der Web-Client zugreifen möchte
  • (?) «Eine optionale Abfrage ist eine Folge von Attribut-Wert-Paaren durch ein Trennzeichen (&) getrennt führen.
  • (#) «Ein optionales Fragment ist oft ein id-Attribut eines bestimmten Elements, und Web-Browser dieses Element in der Ansicht scrollen.

Wenn der Parameter hat ein Epoch ?date=1467708674 dann verwenden.

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

eingeben

Authentifizierungs-URL mit Benutzername: Passwort: Wenn usernaem / Passwort enthält Symbol @
mögen:

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

, dann müssen Sie kodieren URL der @ %40 . Siehe ...

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() Beispiel

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 (-_.!~*')
*/

Sie können window.location anmelden und alle Optionen sehen, die nur für die URL:

window.location.origin

für die gesamte Pfad Verwendung:

window.location.href

gibt es auch Lage. _ _

.host
.hostname
.protocol
.pathname

Dies wird die absolute URL der aktuellen Seite mit JavaScript / jQuery .

  • document.URL

  • $("*").context.baseURI

  • location.href

Wenn es jemanden gibt, die URL und Hash-Tag verketten will, kombiniert zwei Funktionen:

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

Ich habe dies die GET-Variablen auf Streifen aus.

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

Sie können einfach erhalten Sie Ihren Weg js selbst verwenden, window.location oder location geben Sie das Objekt der aktuellen URL

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

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

Um die URL des übergeordneten Fensters erhalten aus einem Iframe:

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

Hinweis: funktioniert nur auf der gleichen Domain

Hier ist ein Beispiel die aktuelle URL mit jQuery und JavaScript zu bekommen:

$(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);
});

Die folgenden sind Beispiele für nützliche Code-Schnipsel, die verwendet werden können - einige der Beispiele verwenden Standard-JavaScript-Funktionen und sind nicht spezifisch für jQuery:

Siehe 8 Nützliche jQuery Snippets Für URL & querystrings .

Mit window.location.href . Dies gibt Ihnen die vollständige URL .

window.location geben Sie die aktuelle URL , und Sie können extrahieren, was Sie von ihm wollen ...

Wenn Sie den Pfad des Root-Site erhalten möchten, verwenden Sie diese:

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

Siehe purl.js . Das wird wirklich helfen und kann auch verwendet werden, abhängig von jQuery. Verwenden Sie es wie folgt aus:

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

var path = location.pathname gibt den Pfad der aktuellen URL (jQuery ist nicht erforderlich). Die Verwendung von window.location ist optional.

Sehr häufig verwendete Top-3 sind diejenigen

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

Alle Browser unterstützt kein Javascript-Fenster-Objekt. Es definiert das Fenster des Browsers.

Die globalen Objekte und Funktionen werden Teil des Fensters Objekt automatisch.

Alle globalen Variablen sind Fenster-Objekte Eigenschaften und alle globalen Funktionen sind seine Methoden.

Das ganze HTML-Dokument ist ein Fenster Eigenschaft zu.

So können Sie window.location Objekt verwenden, um alle url bezogene Attribute zu erhalten.

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

In jstl können wir aktuellen URL-Pfad zugreifen pageContext.request.contextPath Verwendung Wenn Sie einen Ajax-Aufruf tun wollen,

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

Ex: in der Seite http://stackoverflow.com/questions/406192 dies gibt http://stackoverflow.com/controller/path

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top