2009-04-22 13 views
5

Ho inserito un URL assoluto nel mio JavaScript che ho hard coded per window.location.

Non voglio doverlo modificare ogni volta che sto testando la mia app. In PHP avrei gestito questo testando la variabile $ _SERVER ["HTTP_HOST"] per scoprire quale server sono attivo e regolare di conseguenza. Tuttavia, non ho familiarità con Java e mi chiedo se ha un metodo simile? O se forse anche JavaScript avesse un metodo simile?

Il codice è il seguente:

var url = "http://172.17.1.107/store/results/index.jsp"; 
window.location = url; 

Quello che vorrei fare è:

var server = [something that returns just 172.17.1.107 (with or without the http:// is fine)] 
var url = "http://" + server + "/store/results/index.jsp"; 
window.location = url; 

In PHP avrei solo fatto questo:

var server = <?= $_SERVER["HTTP_HOST"] ?> 
var url = "http://" + server + "/store/results/index.php"; 
window.location = url; 

Tutte le idee ? Suppongo che io stia operando partendo dal presupposto che devi fare un URL assoluto per cambiare la posizione della finestra corrente in JavaScript. Se esiste un altro modo per modificare la posizione della finestra in JavaScript senza un URL assoluto, non esitare a offrirlo.

Grazie in anticipo ...

risposta

7

Quello che vi serve è:

request.getServerName() 

Un esempio:

<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
-1

Si dovrebbe avere ricerca di questo, ma in JSP si tratta di:

request.getRemoteHost() 
2

Javascript:

var server = window.location.hostname; 
4

L'oggetto posizione has several properties, e quello vorresti è hostname.

Oppure, è possibile semplicemente utilizzare un URL relativo alla radice e impostare semplicemente la proprietà pathname senza compromettere il business dell'host!

location.pathname = "/store/results/index.jsp"; 
-3

Forse questo potrebbe aiutare.

Sostituirà qualsiasi parola desiderata con qualcosa o niente. Funzionerà anche per la tua richiesta.

var str = "Visit Microsoft!"; 
var res = str.replace("Microsoft", "W3Schools"); 
+1

Sì, certo, e l'acqua è blu. HTF è correlato !!! –