使用 javascript 确定 ip 在 chrome 中有效,在 firefox 或 ie 中无效
我正在使用 javascript 来确定访问者的 IP 地址。不管出于什么原因,它在 Chrome 中工作,而不在 Firefox、IE 或其他浏览器中工作。
这是我的代码:
function getIPAddress() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlHttp.send();
var hostipInfo = xmlHttp.responseText.split("\n");
for (var i = 0; i < hostipInfo.length - 1; i++) {
var ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") return ipAddress[1];
}
return "unknown";
}
在我工作的公司,我使用代理。这可能是代理问题,还是这段代码有问题?谢谢。
刚刚将我的代码部署到我们的测试环境中,在 IE 中,我收到一个弹出窗口,显示“此页面正在访问不受其控制的信息”。这会带来安全风险。你想继续吗?如果我说,是的,它就有效。如果我说不,那就不会。
I am using javascript to determine the visitors ip address. For what ever reason, it works in Chrome and not in Firefox, IE, or other browsers.
Here is my code:
function getIPAddress() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlHttp.send();
var hostipInfo = xmlHttp.responseText.split("\n");
for (var i = 0; i < hostipInfo.length - 1; i++) {
var ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") return ipAddress[1];
}
return "unknown";
}
At the company I'm working for, I am behind a proxy. Could this be a proxy issue, or is there something wrong with this code? Thanks.
Just deployed my code to our test environment, and in IE, I receive a pop up saying 'This page is accessing information that is not under its control. This poses a security risk. Do you want to continue?' If I say, yes, it works. If I say, no, it doesn't.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您打算使用 AJAX(这就是这段代码),我强烈建议您使用第三方包装器,例如 jQuery。这将大大提高跨浏览器兼容性,并允许您将代码缩小到这样的程度。
附加点
正如
Pointy
提到的,如果您的页面运行在与hostip.info
不同的域上,您将需要设置一个本地 PHP像这样获取数据..localGetData.php
新 Ajax
If you're going to use AJAX (which is what this code is), I STRONGLY suggest you use a 3rd party wrapper like jQuery. That will increase cross-browser compatibility greatly and allows you to shrink your code down to something like this.
Additional Point
As
Pointy
mentioned, if your page is running on a different domain thanhostip.info
, you will need to setup a local PHP to fetch the data like this..localGetData.php
New Ajax
for (var i = 0; i < hostipInfo.length - 1; i++) {
将导致返回“unknow”,如果hostipInfo
只有一个元素,则更改为 <代码>for (var i = 0; i < hostipInfo.length; i++) {。for (var i = 0; i < hostipInfo.length - 1; i++) {
will cause to return "unknow" ifhostipInfo
has only one element, change tofor (var i = 0; i < hostipInfo.length; i++) {
.这在 Chrome 中起作用的原因是它支持 CORS,允许您跨域发出此请求。
由于该网站似乎不支持
The reason this works in Chrome is because it supports CORS which allows you to make this request cross domain.
Since the site doesnt appear to support