如何使用 JavaScript 和 PHP 將變數從 Google Maps 傳遞到 MySQL?

Susan Sarandon
發布: 2024-10-20 14:36:30
原創
775 人瀏覽過

How to Pass a Variable from Google Maps to MySQL using JavaScript and PHP?

在JavaScript 和PHP 之間共享資料:將變數從Google 地圖傳遞到MySQL

在Web 中利用JavaScript 和PHP 的功能應用程式之間經常需要交換資料。讓我們考慮一個具體的範例,您需要將從 Google 地圖獲取的 JavaScript 變數傳遞到 PHP 變量,以將其儲存在 MySQL 資料庫中。

假設您有一個名為「lugar」的 JavaScript 變量,它保存緯度和從 Google 地圖獲取的經度座標。目標是將此資料傳輸到同名「$lugar」的 PHP 變數以進行資料庫插入。

使用 jQuery Ajax 的解決方案

要實現此目的,您可以利用 jQuery Ajax,用於與伺服器非同步通訊的流行 JavaScript 函式庫。此技術涉及建立一個額外的PHP 腳本,負責將資料保存在資料庫中:

客戶端(JavaScript)腳本:

<code class="javascript">$.ajax({
    url: "save.in.my.database.php",
    type: "post",
    dataType: "json",
    data: {
        lugar: results[0].geometry.location
    },
    success: function(data){
        alert('saved');
    },
    error: function(){
        alert('error');
    }
});</code>
登入後複製

伺服器端(PHP)腳本:

<code class="php"><?php
if (isset($_POST['lugar'])) {
    // Connect to your database
    // ... Database connection code goes here

    // Prepare your SQL query to insert the data
    $query = "INSERT INTO your_table (lugar) VALUES (?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('s', $_POST['lugar']);

    // Execute the query
    $stmt->execute();

    // Close your database connection
    // ... Database closing code goes here
}
else {
    // Handle the case when the $_POST['lugar'] is not set
    // ... Error handling code goes here
}
?></code>
登入後複製

此解決方案提供了一種將資料從JavaScript 傳輸到PHP 的無縫方法,可讓您將Google 地圖功能與PHP 驅動的資料庫整合。

以上是如何使用 JavaScript 和 PHP 將變數從 Google Maps 傳遞到 MySQL?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!