using javascript to determine ip works in chrome not firefox or 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 t开发者_StackOverflow社区o continue?' If I say, yes, it works. If I say, no, it doesn't.
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.
$.post('http://api.hostip.info/get_html.php', function(data){
alert(data);
});
Additional Point
As Pointy
mentioned, if your page is running on a different domain than hostip.info
, you will need to setup a local PHP to fetch the data like this..
localGetData.php
die(file_get_contents('http://api.hostip.info/get_html.php'));
New Ajax
$.post('localGetData.php', function(data){
alert(data);
});
for (var i = 0; i < hostipInfo.length - 1; i++) {
will cause to return "unknow" if hostipInfo
has only one element, change to for (var i = 0; i < hostipInfo.length; i++) {
.
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
精彩评论