javascript 提交 AJAX 表单后获取访问者的 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10609212/
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
Get IP address of visitor after an AJAX form submit
提问by trante
I have an HTML form. When visitor submits form, a javascript method is invoked. This method sends an AJAX request to my server's php file. My problem is i need to get the visitor's ip address. But because of AJAX request calls php file, $_SERVER['REMOTE_ADDR']gives me my server's address. How can i get visitor's ip, in this case? Thank you
我有一个 HTML 表单。当访问者提交表单时,会调用一个 javascript 方法。此方法将 AJAX 请求发送到我服务器的 php 文件。我的问题是我需要获取访问者的 IP 地址。但是由于 AJAX 请求调用 php 文件,$_SERVER['REMOTE_ADDR']给了我我的服务器地址。在这种情况下,我如何获得访问者的 ip?谢谢
<form onsubmit="sendData(); return false;">
// some data here
</form>
function sendData(){
// do some work, get variables
$.ajax({
url:"/mypage.php",
type:"GET",
data: { name: e },
success : function(data) {
// do some work
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
}
// in mypage.php
public function useData() {
$name=$_GET["name"];
$ip = $_SERVER['REMOTE_ADDR'];
}
回答by Darin Dimitrov
$_SERVER['REMOTE_ADDR']
will give you the IP address of the client. But since presumably you are using the same machine as server andclient you get the same IP which is normal. Once you host your website into a web server and access it remotely from a different machine you will get the address of that remote machine.
$_SERVER['REMOTE_ADDR']
会给你客户端的IP地址。但是因为大概您使用的是同一台机器作为服务器和客户端,所以您获得相同的 IP,这是正常的。一旦您将网站托管到 Web 服务器并从另一台机器远程访问它,您将获得该远程机器的地址。
So there's nothing more you need to do. Your code already works as expected.
因此,您无需再执行任何操作。您的代码已经按预期工作。
回答by MiDri
The ajax request is still originating from the client, it should be giving the clients IP not the servers.
ajax 请求仍然来自客户端,它应该给客户端 IP 而不是服务器。