2013-11-28 73 views
2

在我的PHP頁面,我存儲用戶城市,當他來到我的網站。谷歌API JavaScript代碼裏面的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值。

+0

你可以做到這一點通過Ajax:http://api.jquery.com/jQuery.ajax/然後在服務器上,保存它們的位置... – Leonardo

+0

如果你問如何運行這個JavaScript代碼放在'.php'文件中,你可以簡單地將它放在'<?php'和'?>'標籤之外。 – Charles

+0

可能的重複[參考:爲什麼我的Javascript中的PHP(或其他服務器端)代碼無法工作?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-or-其他的服務器端代碼 - 在 - 我的JavaScript - 不WOR) –

回答

1

也不知道如何將javascript var值設爲php值。

你不能這樣做,因爲Javascript運行在客戶端,瀏覽器和服務器上的php。

1

你也可以很容易地從IP地址訪客所在位置的詳細信息在PHP中:

<?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

1

,因爲JavaScript是運行您不能分配一個Javascript變量值的PHP變量在客戶端Borwser和PHP腳本運行在服務器上。

但有使用POST或GET方法發送回服務器的方式..

你甚至可以使用AJAX/jQuery來做到這一點。

使用jquery的一種方法是最簡單的。這裏是鏈接到它:http://api.jquery.com/jQuery.ajax/

在服務器上創建一個PHP文件調用它storecity.php

<?php 
$city = $_GET['city']; 
$user = $_GET['name']; 
// Write your code to store the variable $city into the database 
?> 

那麼你得到後添加此代碼用戶所在的城市(注意要包括這jQuery庫工作)

$.ajax({ 
    type: "GET", 
    url: "storecity.php", 
    data: { name: "John", city: "Boston" } 
});