首页 > 解决方案 > 如何获取内部 html 数据的值以将值存储到数据库

问题描述

如何将此 JavaScript 变量数据获取到 PHP,以便我可以将纬度和经度数据插入数据库或任何其他方式来获取用户的位置并将其存储在数据库中。

<!DOCTYPE html>
<html>
<body>
  <p>Click the button to get your coordinates.</p>
  <button onclick="getLocation()">Try It</button>
  <p id="demo"></p>
  <script>
    var x = document.getElementById("demo");

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

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude;
    }
  </script>
</body>
</html>

标签: javascriptphpgeolocation

解决方案


似乎您需要使用 AJAX 将您的 javascript 变量的值传递给 PHP。

在您的 HTML 文件 (index.html) 中

索引.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getLocation()">Try It</button>
<script>
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    //AJAX CALL THIS WILL PASS THE VALUE OF JAVASCRIPT TO PHP
    $.ajax({
      type: 'post',
      url: 'ajax-processor.php',
      data: {
        lat: lat,
        long: long
      },
      success: function(html) {
        alert("Success");
      }
    });
  }
</script>

在您的 ajax 文件中 (ajax-processor.php)

$lat = $_POST['lat'];
$long = $_POST['long'];

//your code to insert to the database here using the $lat and $long variable

确保 PHP 文件的 URL 正确。

您可以在我的博客文章中阅读更多关于 AJAX 以及如何将数据从 JavaScript 传递到 PHP:https ://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/


推荐阅读