[英]Save value in Javascript variable from $.get and use it in PHP variable
I am getting some basic info of the visitor on my site using javascript.我正在使用 javascript 在我的网站上获取访问者的一些基本信息。
var userinfo = "";
//printing user info
$.get("http://ipinfo.io", function (response) {
alert("IP: " + response.ip);
alert("Location: " + response.city + ", " + response.region);
alert(JSON.stringify(response, null, 4));
userinfo = (JSON.stringify(response,null,4)); //saving json in js variable (not working, it says undefined)
}, "jsonp");
Then I want to access this value in my PHP variable:然后我想在我的 PHP 变量中访问这个值:
<?php
echo $getuserinfo ; // How to store JS var here in this php var?
?>
The JS variable value is not being saved, what I am doing wrong? JS变量值没有被保存,我做错了什么? And how can I store JS variable value in PHP variable?
以及如何在 PHP 变量中存储 JS 变量值?
You could make a stat page/api that you make a ajax call to from javascript.您可以制作一个统计页面/api,您可以从 javascript 中对其进行 ajax 调用。
$.ajax({
type: "POST",
url: '/setstats.php',
data: {userdata: userinfo},
success: function(){
console.log("Userdata send");
},
dataType: "json"
});
This will first be avalible at a later time then when the page initally loads, but you could now have it saved in the session for the next requests.这将在稍后页面最初加载时首先可用,但您现在可以将其保存在会话中以供下一个请求使用。
You are using jQuery.get
method.您正在使用
jQuery.get
方法。
This method support a parameter called Data此方法支持名为 Data 的参数
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
After it is sent to the server to http://ipinfo.io
it is available in the called script (index.php or what you have as default) in the $_GET
array.在它被发送到服务器到
http://ipinfo.io
它可以在$_GET
数组中的被调用脚本(index.php 或默认的)中使用。
If you send data: {var1: value1, var2: value2}
you will have $_GET["var1"] and $_GET["var2"]
如果你发送
data: {var1: value1, var2: value2}
你将有$_GET["var1"] and $_GET["var2"]
Simply send data: userinfo
and in php do a var_dump($_GET)
and check what you got简单地发送
data: userinfo
并在 php 中做一个var_dump($_GET)
并检查你得到了什么
I solved it by using the PHP version of the API:我通过使用 API 的 PHP 版本解决了它:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
//echo $ip;
return $details;
}
$details = ip_details($userIp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.