Ricevi l'URL corrente con jQuery?
-
03-07-2019 - |
Domanda
Sto usando jQuery. Come posso ottenere il percorso dell'URL corrente e assegnarlo a una variabile?
Esempio di URL:
http://localhost/menuname.de?foo=bar&number=0
Soluzione
Per ottenere il percorso, puoi usare:
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)
Altri suggerimenti
In puro stile jQuery:
$(location).attr('href');
L'oggetto location ha anche altre proprietà, come host, hash, protocollo e nome percorso.
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>');
Funzionerà solo se hai jQuery. Ad esempio:
<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 hai bisogno dei parametri hash presenti nell'URL, window.location.href
potrebbe essere una scelta migliore.
window.location.pathname
=> /search
window.location.href
=> www.website.com/search#race_type=1
Ti consigliamo di utilizzare la window.location incorporata in JavaScript
oggetto.
Basta aggiungere questa funzione in JavaScript e restituirà il percorso assoluto del percorso corrente.
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));
}
Spero che funzioni per te.
window.location è un oggetto in javascript. restituisce i seguenti dati
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 puoi usare
$(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
Questo è un problema più complicato di quanto molti possano pensare. Diversi browser supportano oggetti di posizione JavaScript integrati e parametri / metodi associati accessibili tramite window.location
o document.location
. Tuttavia, diverse versioni di Internet Explorer (6,7) non supportano questi metodi allo stesso modo, ( window.location.href
? window.location.replace ()
non supportato), quindi devi accedervi in ??modo diverso scrivendo continuamente un codice condizionale per tenere premuto Internet Explorer.
Quindi, se hai jQuery disponibile e caricato, puoi anche usare jQuery (posizione), come gli altri menzionati perché risolve questi problemi. Se tuttavia, ad esempio, stai eseguendo un reindirizzamento della geolocalizzazione sul lato client tramite JavaScript (ovvero, utilizzando l'API di Google Maps e i metodi degli oggetti posizione), potresti non voler caricare l'intera libreria jQuery e scrivere il tuo codice condizionale che controlla ogni versione di Internet Explorer / Firefox / ecc.
Internet Explorer rende il gatto codificante front-end infelice, ma jQuery è un piatto di latte.
Solo per il nome host, utilizzare:
window.location.hostname
Funzionerà anche:
var currentURL = window.location.href;
java-script fornisce molti metodi per recuperare l'URL corrente che viene visualizzato nella barra degli indirizzi del browser.
URL test:
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);
funzione:
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();
}
- protocollo « Browser web utilizzano il protocollo Internet seguendo alcune regole per la comunicazione tra le applicazioni WebHosted e client Web (browser). (http = 80 , https (SSL) = 443 , ftp = 21, ecc.)
EX: con numeri di porta predefiniti
<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
- (//) «Host è il nome assegnato a un end-point (macchina su cui risiede la risorsa) su Internet. www.stackoverflow.com - DNS Indirizzo IP di un'applicazione (OR) localhost: 8080 - localhost
I nomi di dominio vengono registrati in base alle regole e alle procedure dell'albero DNS (Domain Name System). Server DNS di qualcuno che gestisce il tuo dominio con indirizzo IP a fini di indirizzamento. Nella gerarchia del server DNS il nome root di uno stackoverlfow.com è com.
gTLDs - com « stackoverflow (OR) in « co « google
Sistema locale è necessario mantenere i domini che non sono PUBBLICI nei file host.
localhost.yash.com «localhsot - sottodominio (
web-server
), yash.com - maindomain (
).
myLocalApplication.com 172.89.23.777
- (/) «Il percorso fornisce informazioni sulla risorsa specifica all'interno dell'host a cui il client Web desidera accedere
- (?) «Una query facoltativa è passare una sequenza di coppie attributo-valore separate da un delimitatore (& amp;).
- (#) «Un frammento facoltativo è spesso un attributo id di un elemento specifico e i browser Web scorreranno questo elemento in vista.
Se il parametro ha un Epoch ? date = 1467708674
quindi utilizza.
var epochDate = 1467708674; var date = new Date( epochDate );
URL di autenticazione con nome utente: password, se usernaem / password contiene il simbolo @
come:
Username = `my_email@gmail`
Password = `Yash@777`
quindi devi codificare l'URL @
come %40
. Consulta ...
http://my_email%40gmail.com:Yash%40777@www.my_site.com
encodeURI ()
(vs) encodeURIComponent ()
esempio
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 (-_.!~*')
*/
Puoi registrare window.location e vedere tutte le opzioni, solo per l'uso dell'URL:
window.location.origin
per l'intero percorso utilizzare:
window.location.href
c'è anche la posizione. _ _
.host
.hostname
.protocol
.pathname
Se c'è qualcuno che vuole concatenare URL e il tag hash, combina due funzioni:
var pathname = window.location.pathname + document.location.hash;
Ho questo per eliminare le variabili GET.
var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
Puoi semplicemente ottenere il tuo percorso usando js stesso, window.location
o location
ti darà l'oggetto dell'URL corrente
console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
var currenturl = jQuery(location).attr('href');
Per ottenere l'URL della finestra padre da un iframe:
$(window.parent.location).attr('href');
NB: funziona solo sullo stesso dominio
Ecco un esempio per ottenere l'URL corrente utilizzando 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);
});
I seguenti sono esempi di utili frammenti di codice che possono essere utilizzati & # 8211; alcuni esempi utilizzano funzioni JavaScript standard e non sono specifici di jQuery:
Vedi 8 utili frammenti jQuery per URL & # 8217; s & amp; Querystrings .
Usa window.location.href . Questo ti darà il URL completo .
window.location ti darà l'attuale URL e puoi estrarre ciò che vuoi da esso ...
Se vuoi ottenere il percorso del sito radice, usa questo:
$(location).attr('href').replace($(location).attr('pathname'),'');
Vedi purl.js . Ciò sarà di grande aiuto e può anche essere utilizzato, a seconda di jQuery. Usalo in questo modo:
$.url().param("yourparam");
var path = location.pathname
restituisce il percorso dell'URL corrente (non è necessario jQuery). L'uso di window.location
è facoltativo.
I primi 3 usati molto comunemente sono
1. window.location.hostname
2. window.location.href
3. window.location.pathname
Tutti i browser supportano l'oggetto finestra Javascript. Definisce la finestra del browser.
Gli oggetti e le funzioni globali diventano automaticamente parte dell'oggetto finestra.
Tutte le variabili globali sono proprietà degli oggetti finestra e tutte le funzioni globali sono i suoi metodi.
Anche l'intero documento HTML è una proprietà di finestra.
Quindi puoi usare l'oggetto window.location per ottenere tutti gli attributi relativi all'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);
In jstl possiamo accedere al percorso dell'URL corrente utilizzando pageContext.request.contextPath
, se desideri effettuare una chiamata Ajax,
url = "${pageContext.request.contextPath}" + "/controller/path"
Esempio: nella pagina http://stackoverflow.com/questions/406192
questo darà http://stackoverflow.com/controller/path