javascript 使用jQuery查找IP地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14251041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find IP address using jQuery
提问by user1929236
I tried to get my IP using the following code:
我尝试使用以下代码获取我的 IP:
$.getJSON("http://jsonip.appspot.com?callback=?", function(data){ip=data.ip});
But it doesn't seems to work for me. Please Help.
但它似乎对我不起作用。请帮忙。
Thanks in advance.
提前致谢。
回答by Geuis
You can use this site to acquire your IP with JSON.
您可以使用此站点通过 JSON 获取您的 IP。
回答by Harsh Baid
You need to send a ajax request to your backend web server and respond to ajax request with the requesting client's ip back from the server. The code will change depending on the language of your web application.
您需要向后端 Web 服务器发送 ajax 请求,并使用从服务器返回的请求客户端的 ip 来响应 ajax 请求。代码将根据您的 Web 应用程序的语言而改变。
JavaScript itself has no way of reading the IP address of the local computer and so for JavaScript to obtain that information we need to use a different language to obtain the information.
JavaScript 本身无法读取本地计算机的 IP 地址,因此为了让 JavaScript 获取该信息,我们需要使用不同的语言来获取信息。
Several snippets for server-side code options
服务器端代码选项的几个片段
In JSP
在 JSP 中
ip = '<%=request.getRemoteAddr()%>';
In PHP
在 PHP 中
ip = "<?php echo $_SERVER['REMOTE_ADDR']?>";
In ASP
在 ASP 中
ip = '<%= Request.ServerVariables("REMOTE_ADDR")%>';
In ASP.NET
在 ASP.NET 中
ip = '<%= Request.UserHostAddress>';
In Cold Fusion
在冷聚变中
ip = '<cfoutput>#cgi.remote_addr#</cfoutput>';
Reference: Obtaining Your Visitor's IP Address
参考:获取访问者的 IP 地址
回答by Anshu
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
回答by sri_bb
Get your IP with jQuery
使用 jQuery 获取您的 IP
you can get your public IP address with one line of JS? There is a free service that offers this for you and a get request is all that you need to do:
你可以用一行JS来获取你的公共IP地址吗?有一项免费服务可以为您提供此服务,您只需要一个 get 请求即可:
$.get('http://jsonip.com/', function(r){ console.log(r.ip); });
For the above snippet to work, your browser will have to support CORS (cross-origin request sharing). Otherwise a security exception would be thrown. In older browsers, you can use this version, which uses a JSON-P request:
要使上述代码段起作用,您的浏览器必须支持 CORS(跨域请求共享)。否则将引发安全异常。在较旧的浏览器中,您可以使用此版本,它使用 JSON-P 请求:
$.getJSON('http://jsonip.com/?callback=?', function(r){ console.log(r.ip); });