php - 通过 ajax 和 jquery 将变量发送到 php

标签 php jquery ajax variables geolocation

我想通过 html5-geolocation 请求用户地理定位并将其发送到下一页 有人告诉我必须使用 ajax/jquery,所以这是我的代码:

<form action="response.php">
        <button onclick="getLocation()">Start</button>

<script>

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function successFunction(position) {
   var lat = position.coords.latitude;
   var longi = position.coords.longitude;

    $.ajax({
  type: "POST",
  url: "response.php",
  data: { latitude: lat, longitude: longi }
  }).done(function( msg ) {
  alert( "Data Saved: " + msg );
});
}
</script>
</form>

现在我想在我的 response.php 页面上“回显”纬度和经度 但我不知道该怎么做:'( 我试过这个:

$latitude = $_POST["latitude"]; 
echo $latitude; 

但是页面是空白的

最佳答案

试试这个:

index.html:

<html>
<head></head>
<body>
    <form action="response.php" method="post">
      <input type="hidden" id="latitude" name="latitude" value="" />
      <input type="hidden" id="longitude" name="longitude" value="" />
      <input type="submit" value="Start" />
    </form>
</body>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    function getLocation() {

         var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
         };

        function success(pos) {
           successFunction(pos);
        };

        function error(err) {
            console.warn('ERROR(' + err.code + '): ' + err.message);
        };

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, error,options);
        } else { 
            //x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function successFunction(position) {
       var lat = position.coords.latitude;
       var longi = position.coords.longitude;

        $('#latitude').val(lat);
        $('#longitude').val(longi);
    }
    getLocation();
</script>
</html>

response.php:

<?php
    $latitude = $_POST["latitude"]; 
    $longitude = $_POST["longitude"]; 
    echo "Latitude:".$latitude."</br>";
    echo "longitude:".$longitude;
?>

只需创建 index.html 复制并粘贴此代码并确保 response.php 像这样。

/yourprojectdirectory/index.html
/yourprojectdirectory/response.php

关于php - 通过 ajax 和 jquery 将变量发送到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30618459/

相关文章:

javascript - Jquery帮助加载Json数据

javascript - 可以从 JS 客户端获取 POST 请求的 Java 服务器

php - MySQL:更新具有相同值的字段

javascript - 实时计算?

javascript - CSS 中的最小/最大绝对位置

javascript - jQuery 动画最大宽度溢出问题

javascript - onBlur 事件覆盖 jQuery UI 事件

javascript - 在ajax中传递变量成功

php - 使用 PHP 解析 Google 海拔高度的结果

php - 在连接数据库之前执行工作