Sto usando jQuery. Come posso ottenere il percorso dell’URL corrente e assegnarlo a una variabile?
URL di esempio:
http://localhost/menuname.de?foo=bar&number=0
Per ottenere il percorso, puoi utilizzare:
var pathname = window.location.pathname; // Returns path only var url = window.location.href; // Returns full URL
In puro stile jQuery:
$(location).attr('href');
L’object posizione ha anche altre proprietà, come host, hash, protocollo e 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('');
Funzionerà solo se hai jQuery. Per esempio:
$(location).attr('href'); // http://www.refulz.com:8082/index.php#tab2 $(location).attr('pathname'); // index.php
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 l’object window.location
incorporato di JavaScript.
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 object 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
Questa è una questione più complicata di quanto molti possano pensare. Diversi browser supportano oggetti di posizione JavaScript e parametri / metodi associati accessibili tramite window.location
o document.location
. Tuttavia, diversi tipi di Internet Explorer (6,7) non supportano questi metodi allo stesso modo, ( window.location.href
? window.location.replace()
non supportato), quindi è necessario accedervi in modo diverso scrivendo condizionale codice tutto il tempo per tenere in mano Internet Explorer.
Quindi, se hai jQuery disponibile e caricato, potresti anche usare jQuery (posizione), come menzionato dagli altri perché risolve questi problemi. Se tuttavia, per esempio, stai eseguendo il reindirizzamento della geolocalizzazione lato client tramite JavaScript (ovvero utilizzando l’API di Google Maps e i metodi dell’object posizione), potresti non voler caricare l’intera libreria jQuery e scrivere il codice condizionale che controlla ogni versione di Internet Explorer / Firefox / ecc.
Internet Explorer rende infelice la codifica del front-end, ma jQuery è un piatto di latte.
Solo per il nome host, utilizzare:
window.location.hostname
Questo funzionerà anche:
var currentURL = window.location.href;
È ansible 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
java-script fornisce molti metodi per recuperare l’URL corrente che viene visualizzato nella barra degli indirizzi del browser.
URL di test: http://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in/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(); }
EX: con numeri di porta predefiniti
//:/ https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy http://stackoverflow.com:80/
I nomi di dominio sono registrati dalle regole e procedure dell'albero del Domain Name System (DNS). Server DNS di qualcuno che gestisce il tuo dominio con indirizzo IP per scopi di indirizzamento. Nella gerarchia del server DNS il nome di radice di uno stackoverlfow.com è com.
gTLDs - com « stackoverflow (OR) in « co « google
Sistema locale è necessario mantenere i domini che non sono PUBBLICI in file host. localhost.yash.com « localhsot - subdomain(
web-server
), yash.com - maindomain(
Proxy-Server
). myLocalApplication.com 172.89.23.777
). myLocalApplication.com 172.89.23.777
Se il parametro ha ?date=1467708674
quindi utilizzare.
var epochDate = 1467708674; var date = new Date( epochDate );
URL
URL di autenticazione con nome utente: password, se usernaem / password contiene simbolo @
piace:
Username = `[email protected]` password = `[email protected]`
allora hai bisogno di codificare l'URL @
come %40
. Fare riferimento...
http://my_email%40gmail.com:Yash%[email protected]_site.com
Ciò restituirà l’ URL assoluto della pagina corrente utilizzando JavaScript / jQuery .
document.URL
$("*").context.baseURI
location.href
Se c’è qualcuno che vuole concatenare l’ URL e il tag hash, combina due funzioni:
var pathname = window.location.pathname + document.location.hash;
Ho questo per rimuovere le variabili GET.
var loc = window.location; var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
var currenturl = jQuery(location).attr('href');
Per ottenere l’URL della finestra genitore dall’interno di un iframe:
$(window.parent.location).attr('href');
NB: funziona solo sullo stesso dominio
Ecco un esempio per ottenere l’URL corrente 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); });
Di seguito sono riportati esempi di utili snippet di codice che possono essere utilizzati: alcuni degli esempi utilizzano le funzioni JavaScript standard e non sono specifici per jQuery:
Vedi 8 utili frammenti jQuery per URL e Querystring .
Usa window.location.href . Questo ti darà l’ URL completo.
Puoi semplicemente ottenere il tuo percorso usando js stesso, window.location
o location
ti darà l’object dell’URL corrente
console.log("Origin - ",location.origin); console.log("Entire URL - ",location.href); console.log("Path Beyond URL - ",location.pathname);
window.location ti darà l’ URL corrente e potrai estrarre tutto ciò che vuoi da esso …
Se vuoi ottenere il percorso del sito root, usa questo:
$(location).attr('href').replace($(location).attr('pathname'),'');
var path = location.pathname
restituisce il percorso dell’URL corrente in jQuery. Non c’è bisogno di usare la window
.
Vedi purl.js. Questo sarà davvero d’aiuto e può anche essere usato, a seconda di jQuery. Usalo in questo modo:
$.url().param("yourparam");
// get current URL $(location).attr('href'); var pathname = window.location.pathname; alert(window.location);
I più comuni sono quelli top 3 usati
1. window.location.hostname 2. window.location.href 3. window.location.pathname
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
In jstl possiamo accedere al percorso url corrente usando pageContext.request.contextPath
, Se vuoi fare una chiamata ajax,
url = "${pageContext.request.contextPath}" + "/controller/path"
Es: nella pagina http://stackoverflow.com/questions/406192
questo darà http://stackoverflow.com/controller/path