我需要以某种方式检索客户端的IP地址使用JavaScript;没有服务器端代码,甚至没有SSI。
然而,我并不反对使用免费的第三方脚本/服务。
我需要以某种方式检索客户端的IP地址使用JavaScript;没有服务器端代码,甚至没有SSI。
然而,我并不反对使用免费的第三方脚本/服务。
当前回答
试试这个:http://httpbin.org/ip(或https://httpbin.org/ip)
https的示例:
$.getJSON('https://httpbin.org/ip', function(data) {
console.log(data['origin']);
});
来源:http://httpbin.org/
其他回答
好吧,我偏离了这个问题,但我今天有一个类似的需求,尽管我无法使用Javascript从客户端找到ID,但我做了以下工作。
服务器端:-
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
使用Javascript
var ip = $get("uip").innerHTML;
我使用ASP。Net Ajax,但您可以使用getElementById而不是$get()。
发生的事情是,我在页面上有一个隐藏的div元素,用户的IP从服务器呈现。而在Javascript中,我只是加载这个值。
这可能对像你这样有类似需求的人(比如我,但我还没有弄清楚)有帮助。
干杯!
在你的页面中包含以下代码:<script type="text/javascript" src="http://l2.io/ip.js"></script>
点击这里了解更多
你可以使用userinfo。IO javascript库。
<script type="text/javascript" src="userinfo.0.0.1.min.js"></script>
UserInfo.getInfo(function(data) {
alert(data.ip_address);
}, function(err) {
// Do something with the error
});
您还可以使用requirejs来加载脚本。
它将为您提供访问者的IP地址,以及有关其位置的一些数据(国家、城市等)。它基于maxmind geoip数据库。
声明:这个库是我写的
有一种更简单和免费的方法,不需要访问者的任何许可。
它包括向http://freegeoip.net/json提交一个非常简单的Ajax POST请求。一旦收到JSON格式的位置信息,您就可以通过更新页面或重定向到新页面来做出相应的反应。
以下是提交位置信息请求的方法:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
console.log(location)
}
} );
Appspot.com回调服务不可用。ipinfo。IO似乎在工作。
我做了一个额外的步骤,检索所有的地理信息使用AngularJS。(感谢里卡多)来看看。
<div ng-controller="geoCtrl">
<p ng-bind="ip"></p>
<p ng-bind="hostname"></p>
<p ng-bind="loc"></p>
<p ng-bind="org"></p>
<p ng-bind="city"></p>
<p ng-bind="region"></p>
<p ng-bind="country"></p>
<p ng-bind="phone"></p>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular-route.min.js"></script>
<script>
'use strict';
var geo = angular.module('geo', [])
.controller('geoCtrl', ['$scope', '$http', function($scope, $http) {
$http.jsonp('http://ipinfo.io/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
$scope.hostname = data.hostname;
$scope.loc = data.loc; //Latitude and Longitude
$scope.org = data.org; //organization
$scope.city = data.city;
$scope.region = data.region; //state
$scope.country = data.country;
$scope.phone = data.phone; //city area code
});
}]);
</script>
工作页面在这里:http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html