在我的php页面中,当用户来到我的网站时,我会存储他们所在的城市。
这是我从网上得到的谷歌API。
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
<script type="text/javascript">
if(google.loader.ClientLocation)
{
visitor_lat = google.loader.ClientLocation.latitude;
visitor_lon = google.loader.ClientLocation.longitude;
visitor_city = google.loader.ClientLocation.address.city;
visitor_region = google.loader.ClientLocation.address.region;
visitor_country = google.loader.ClientLocation.address.country;
visitor_countrycode = google.loader.ClientLocation.address.country_code;
document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
}
</script>
我需要将其存储为PHP变量。有人能告诉我如何在php页面中使用它吗?
我知道echo
和<html> to </html>
的传统方法,并把上面的代码放在里面。但想知道其他更好的方法吗?
我也不知道如何将javascript变量分配给php值。
也不知道如何将javascript的var值转换为php值。
您不能这样做,因为Javascript在客户端、浏览器和服务器上的php中运行。
您还可以从php:中的IP地址轻松获取访问者的位置详细信息
<?php
require_once("userip/ip.codehelper.io.php");
require_once("userip/php_fast_cache.php");
$_ip = new ip_codehelper();
$real_client_ip_address = $_ip->getRealIP();
$visitor_location = $_ip->getLocation($real_client_ip_address);
$guest_ip = $visitor_location['IP'];
$guest_country = $visitor_location['CountryName'];
$guest_city = $visitor_location['CityName'];
$guest_state = $visitor_location['RegionName'];
echo "IP Address: ". $guest_ip. "<br/>";
echo "Country: ". $guest_country. "<br/>";
echo "State: ". $guest_state. "<br/>";
echo "City: ". $guest_city. "<br/>";
?>
有关详细信息,请访问此处http://www.a2zwebhelp.com/visitor-location-in-php
您不能将Javascript变量值分配给PHP变量,因为Javascript在Client Borwser上运行,而PHP脚本在Server上运行。
但是有一种方法可以使用POST或GET方法将其发送回服务器。。
您甚至可以使用AJAX/JQuery来完成此操作。
使用Jquery的方法之一是最简单的。这是它的链接:http://api.jquery.com/jQuery.ajax/
在服务器上创建一个名为storecity.PHP 的PHP文件
<?php
$city = $_GET['city'];
$user = $_GET['name'];
// Write your code to store the variable $city into the database
?>
然后在获得用户所在城市后添加此代码(注意,要包含Jquery Library才能工作)
$.ajax({
type: "GET",
url: "storecity.php",
data: { name: "John", city: "Boston" }
});