JS坐标->PHP脚本-如何在PHP中保留变量

JS Coordinates -> PHP Script - How do I keep the variables in PHP?

本文关键字:PHP 保留 变量 脚本 gt JS 坐标      更新时间:2023-09-26

我有一个正在尝试改编的脚本。因此,脚本执行成功。然而,我正在尝试停止脚本的最后阶段,并将结果保存在PHP中。我读过各种各样的帖子,但不确定哪里出了问题。我知道JS是客户端,PHP是服务器端;根据我所读到的内容,在不刷新的情况下传递变量的唯一方法是XMLHttp或Ajax。

现在,浏览器使用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文件中的变量。

非常感谢您的帮助!如果我遗漏了什么,我会提前道歉——我确实读了很多关于这方面的帖子,但没有找到解决方案。

如果要保留国家/地区字符串,可以使用$_SESSION变量

<?php session_start();
/* Your code here */
$geodata['country'] = $_SESSION['country'];

现在,您可以通过调用$_SESSION["country"]对country字符串执行任何操作您必须在要在中使用$_SESSION['country']变量的每个php前面加上SESSION_start()