Domanda

Ho andare un URL assoluto nel mio JavaScript che ho codificato duro per window.location.

Non voglio avere a cambiare questo ogni volta che sto testando la mia app. In PHP avrei gestito questo testando il $ _SERVER [ "HTTP_HOST"] variabile per scoprire quale server sono su, e regolare di conseguenza. Tuttavia, io non sono come familiarità con Java e mi chiedo se ha un metodo simile? O se magari anche JavaScript aveva 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 semplicemente fatto questo:

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

Tutte le idee? Suppongo che sto operando sotto l'ipotesi che si deve fare un URL assoluto per cambiare la posizione della finestra corrente in JavaScript. Se non v'è altro modo per cambiare la posizione della finestra in JavaScript, senza un URL assoluto, non esitate a offrire che pure.

Grazie in anticipo ...

È stato utile?

Soluzione

Quello che vi serve è:

request.getServerName()

Un esempio:

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

Altri suggerimenti

L'oggetto ha diverse proprietà , e quello che ci si vuole è hostname .

In alternativa, è possibile scegliere di utilizzare solo un URL relativo alla cartella principale e basta impostare i href="http://www.w3schools.com/HTMLDOM/prop_loc_pathname.asp" pasticcio proprietà e non con il business di accoglienza a tutti!

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

Javascript:

var server = window.location.hostname;

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

request.getRemoteHost()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top