简体   繁体   English

javascript获取客户端IP

[英]javascript getting client ip

Hi I found how to get client ip by answer here: Can I perform a DNS lookup (hostname to IP address) using client-side Javascript? 嗨,我发现如何通过此处的答案获取客户端ip: 我可以使用客户端Javascript执行DNS查找(从主机名到IP地址)吗?

But I don't understand how to use it. 但是我不知道如何使用它。

This is what I have: 这就是我所拥有的:

var user;
if ($('#user-id').length) {
    user = $('#user-id').text();
} else {
    http://jsonip.appspot.com/?callback=getip
    function getip(json){
       user = json.ip;
    }
}

I don't understand how to include the url and how to use the getip function. 我不明白如何包含网址以及如何使用getip函数。

I need to set the user to the ip address in the else. 我需要将用户设置为else中的IP地址。

Thanks! 谢谢!

Using jQuery, you could make a JSONP call: 使用jQuery,您可以进行JSONP调用:

$.getJSON('http://jsonip.appspot.com/?callback=?',
        function(data){
          alert(data.ip);
        });

Probably easier to understand - an alternative, without jQuery, would be: 可能更容易理解-没有jQuery的替代方法是:

<script type="text/javascript">
    function getip(data){
      alert(data.ip);
    }
</script>
<script type="text/javascript" src="http://jsonip.appspot.com/?callback=getip">
</script>

Note that when you include http://jsonip.appspot.com/?callback=getip as a script in your HTML you get valid JavaScript as response: 请注意,当您将http://jsonip.appspot.com/?callback=getip作为脚本包含在HTML中时,您将获得有效的JavaScript作为响应:

getip({"ip": "147.234.2.5", "address":"147.234.2.5"});

This line executes your function with the proper parameter. 该行使用适当的参数执行您的功能。 Note that the function's name is given to it by query string. 请注意,函数名称是由查询字符串赋予的。

You could use something like this: 您可以使用如下形式:

<script type="text/javascript">
  var userip;
</script>
...
<script type="text/javascript" src="http://l2.io/ip.js?var=userip"</script>
...
<script type="text/javascript">
  document.write("Your IP is :", userip);
</script>

Here is the url of this library: http://l2.io/ 这是该库的URL: http : //l2.io/

You can only access your domain from JavaScript, you cannot do cross-domain communication with JavaScript unless you do the communication with iframes . 您只能通过JavaScript访问域,除非使用iframe进行通信,否则就不能使用JavaScript进行跨域通信。

If you have a dynamic backend such as PHP, Java, Python, Ruby, CGI, etc you can easily fetch the IP address from the user visiting your page. 如果您拥有动态后端,例如PHP,Java,Python,Ruby,CGI等,则可以轻松地从访问页面的用户那里获取IP地址。 Each language has their own mechanism. 每种语言都有自己的机制。

You've got a random, free-floating URL in your javascript syntax. 您的javascript语法中有一个随机的,自由浮动的URL。

This is how to make remote JSON request with jquery. 这是使用jquery发出远程JSON请求的方法。

http://api.jquery.com/jQuery.getJSON/ http://api.jquery.com/jQuery.getJSON/

I would suggest you get more familiar with javascript in general. 我建议您大致上更熟悉javascript。

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

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