2015-03-03 43 views
0

我有一個腳本,我正在嘗試適應。如此,腳本成功執行。但是,我試圖停止腳本的最後階段並將結果保留在PHP中。我已閱讀各種帖子,但不知道我哪裏錯了。我明白JS是客戶端,PHP是服務器端;從我讀過的內容來看,傳遞變量而不刷新的唯一方法是XMLHttp或Ajax。JS座標 - > PHP腳本 - 我如何保持PHP中的變量?

現在,瀏覽器使用Javascript獲取地理位置座標。它將這些座標發送到一個php文件,其中座標用於獲取國家名稱。國家名稱然後被髮回到在瀏覽器中更新的Javascript。一切都很好,除了我不希望Javascript用國名更新瀏覽器;我想在PHP文件中進一步使用國家名稱,然後根據其他PHP腳本回顯/打印不同的返回值。但是,我無法讓PHP文件回顯/打印變量 - 每次顯示常量但不顯示國家名稱的值。 (出現空?)

JS腳本:

if (navigator.geolocation) { 
navigator.geolocation.getCurrentPosition(GEOprocess, GEOdeclined); }else{ 
document.getElementById('geo').innerHTML = 'Pricing not available. Please 
upgrade your browser or visit the Pricing page.'; 
} 
// this is called when the browser has shown support of  
navigator.geolocation 
function GEOprocess(position) { 
// update the page to show we have the lat and long and explain what we do next 
var lat = position.coords.latitude; 
var lng = position.coords.longitude; 
document.getElementById('geo').innerHTML = 'Latitude: ' + lat + ' Longitude: ' + lng; 

// now we send this data to the php script behind the scenes with the GEOajax function 
GEOajax("geo.php?latlng=" + position.coords.latitude + "," +  
position.coords.longitude); 
} 
// this is used when the visitor bottles it and hits the "Don't Share" option 
function GEOdeclined(error) { 
document.getElementById('geo').innerHTML = 'Error: ' + error.message; 
} 
// this checks if the browser supports XML HTTP Requests and if so which method 
if (window.XMLHttpRequest) { 
xmlHttp = new XMLHttpRequest(); 
}else if(window.ActiveXObject){ 
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
// this calls the php script with the data we have collected from the  
geolocation lookup 
function GEOajax(url) { 
xmlHttp.open("GET", url, true); 
xmlHttp.onreadystatechange = updatePage; 
xmlHttp.send(); 
} 

// this reads the response from the php script and updates the page with it's output 
function updatePage() { 
if (xmlHttp.readyState == 4) { 
var response = xmlHttp.responseText; 
document.getElementById("geo").innerHTML = '' + response; 
} 
} 

PHP腳本是:

<?php 
$url = 'http://maps.google.com/maps/api/geocode/xml? 
latlng='.htmlentities(htmlspecialchars(strip_tags($_GET['latlng']))).'&sensor=true'; 
$xml = simplexml_load_file($url); 

foreach($xml->result->address_component as $component){ 
if($component->type=='country'){ 
    $geodata['country'] = $component->long_name; 
} 
} 
echo $geodata['country']; 
?> 

我預期,我需要做的事情在JS文件停止更新過程;我試圖註釋掉更新部分,但是當我在php文件中使用echo/print來查看可變數據時,這並不起作用。當前的腳本可以工作,但我想停止更新JS部分 - 我只想保留和使用PHP文件中的變量。

任何幫助非常感謝!如果我錯過了某些東西,我會提前道歉 - 我曾閱讀過許多文章,但沒有找到解決方案。

回答

1

如果你想保持國家的字符串,可以通過調用$ _SESSION [「國家」]使用$ _SESSION變量

<?php session_start(); 

/* Your code here */ 

$geodata['country'] = $_SESSION['country']; 

現在你可以做任何你想要與該國的字符串。 您必須在每個使用$ _SESSION ['country']變量的php前加上session_start();.

+0

感謝您的幫助!實際上,我改變了我的電話 - 而不是使用PHP腳本,我合併爲一個,然後相應地更新。 – 2015-03-03 22:46:55