简体   繁体   English

JSP或JavaScript等效于PHP的$ _SERVER [“HTTP_HOST”]?

[英]JSP or JavaScript equivalent to PHP's $_SERVER[“HTTP_HOST”]?

I've go an absolute URL in my JavaScript that I have hard coded for window.location. 我在我的JavaScript中使用了一个绝对URL,我为window.location编写了硬编码。

I don't want to have to change this every time I am testing my app. 我不想每次测试我的应用程序时都要更改它。 In PHP I would have handled this by testing the $_SERVER["HTTP_HOST"] variable to find out what server I am on, and adjust accordingly. 在PHP中,我会通过测试$ _SERVER [“HTTP_HOST”]变量来找出我所在的服务器并进行相应调整。 However, I'm not as familiar with Java and am wondering if it has a similar method? 但是,我对Java并不熟悉,并且想知道它是否有类似的方法? Or if maybe even JavaScript had a similar method? 或者甚至可能是JavaScript有类似的方法?

The code is as follows: 代码如下:

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

What I would like to do is: 我想做的是:

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 I would have just done this: 在PHP中我会这样做:

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

Any ideas? 有任何想法吗? I suppose I'm operating under the assumption that you have to do an absolute URL to change the location of the current window in JavaScript. 我想我的运作是假设您必须使用绝对URL来更改JavaScript中当前窗口的位置。 If there is another way to change the window location in JavaScript without an absolute URL, please feel free to offer that as well. 如果还有其他方法可以在没有绝对URL的情况下更改JavaScript中的窗口位置,请随时提供。

Thanks in advance... 提前致谢...

What you need is: 你需要的是:

request.getServerName()

An example: 一个例子:

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

The location object has several properties , and the one you'd want is hostname . location对象有几个属性 ,你想要的是hostname

Or, you can optionally just use a root-relative URL and just set the pathname property and not mess with the host business at all! 或者,您可以选择使用根相对URL,只需设置路径名属性,而不是干扰主机业务!

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

使用Javascript:

var server = window.location.hostname;

你真的应该搜索这个,但在JSP中它是:

request.getRemoteHost()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM