使用Cookie将地理位置从JavaScript发布到PHP


Posting GeoLocation From JavaScript to PHP using Cookies

我正试图使用Cookie将GoeLocation坐标从JavaScript发送到PHP,我收到了Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 通知

我的文件名是samepage.php,我想把它发布在同一个页面上。

我的代码:

<html>
<head>
<title>Test Geo Location</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
}
$( document ).ready(function() {
$.cookie("data",{getlat:$("#getlat").val(),getlon:$("#getlon").val()});
});
</script>
</head>
<body onload="getLocation();">
<input type="text" id="getlat" name="getlat" value="<?php echo $_POST['polat']; ?>" /> 
<input type="text" id="getlon" name="getlon" value="<?php echo $_POST['polon']; ?>" />
<?php
$data = json_decode($_COOKIE["data"]);
$lat = $data["getlat"];
$lon = $data["getlon"];
?>
</body>
</html>

您需要确保以下几点:1) php代码在服务器端运行;2) javascript代码在客户端运行;3) 默认情况下,jQuery不支持cookie操作。请参阅相关问题

4) 在phpjsondecode函数中,将返回stdClass对象,而不是数组。请参阅json_decode

您需要做的是:1) 包含cookie jquery插件2) 首先通过js函数设置cookie,然后调用phpURL

我和你分享了一个修订版,你会得到你想要的(你需要先下载jquery.cookie.js)。

<html>
<head>
<title>Test Geo Location</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
}
function doSubmit(){
    $.cookie("data",'{'"getlat'":' + $("#getlat").val() + ','"getlon'":' + $("#getlon").val() + '}');
    document.form1.submit();
}
$( document ).ready(function() {

});
</script>
</head>
<body onload="getLocation();">
<form name="form1">
<input type="text" id="getlat" name="getlat" value="<?php echo $_POST['polat']; ?>" /> 
<input type="text" id="getlon" name="getlon" value="<?php echo $_POST['polon']; ?>" />
<input type="button" value="submit" onclick = "doSubmit()">
</form>
<?php
$data = json_decode($_COOKIE["data"]);
$lat = $data->getlat;
$lon = $data->getlon;
?>
</body>
</html>