简体   繁体   English

如何获取内部html数据的值以将值存储到数据库

[英]How to get the value of inner html data for storing the value to database

How do I get this JavaScript variable data to PHP, so that I can insert Latitude and Longitude data to the database or any other way to get the user's location and store it in the database. 如何将这些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> 

it seems like you need to use AJAX to pass the value of your javascript variable to PHP. 似乎您需要使用AJAX将javascript变量的值传递给PHP。

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

index.html index.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>

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

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

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

Make sure that the URL for the PHP file is correct. 确保PHP文件的URL正确。

You may read more about AJAX and how to pass data from JavaScript to PHP in my blog post: https://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/ 您可以在我的博客文章中了解有关AJAX以及如何将数据从JavaScript传递到PHP的更多信息: https : //www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM