【问题标题】:Insert into db from Javascript GPS code从 Javascript GPS 代码插入数据库
【发布时间】:2016-10-17 10:22:01
【问题描述】:

我有一个 GPS 脚本,我需要在后台分别将其实现到我的表单中。

但是,在我继续使用表单实现它之前,我需要了解如何将纬度和经度分别插入到数据库中名为“long”和“lat”的两个字段中。

我已设法将它们分成两个 div,但仍然无法将其放入我的数据库中。

他是完整的GPS页面代码:

    <script>
        var latitude    = 0;
        var longitude   = 0;

function geoFindMe() {
  var output = document.getElementById("show");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    latitude  = position.coords.latitude;
    longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=20&size=300x300&sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating...</p>";
  fillLatitudeLongitudeDivs();
  navigator.geolocation.getCurrentPosition(success, error);
}

function fillLatitudeLongitudeDivs(){
    document.getElementById("latitude").innerHTML = latitude;
    document.getElementById("longitude").innerHTML = longitude;
}

function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
            case "always":
            return callback(true);
            case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
    window.gBrowser.selectedBrowser,
    "geolocation",
    message,
    "geo-notification-icon",
    {
        label: "Share Location",
        accessKey: "S",
        callback: function(notification) {
            done = true;
            callback(true);
        }
    }, [
    {
        label: "Always Share",
        accessKey: "A",
        callback: remember("always", true)
    },
    {
        label: "Never Share",
        accessKey: "N",
        callback: remember("never", false)
    }
    ], {
        eventCallback: function(event) {
            if (event === "dismissed") {
                if (!done) callback(false);
                done = true;
                window.PopupNotifications.remove(self);
            }
        },
        persistWhileVisible: true
    });
}

prompt(window,
"extensions.foo-addon.allowGeolocation",
"Foo Add-on wants to know your location.",
function callback(allowed) { alert(allowed); });
</script>

<p><button onclick="geoFindMe()">Locate</button></p>
<div id="show"></div>

 <?php if(isset($_POST['sub'])){ $lat = $_post['lat']; $lat = $_post['long']; echo $lat; } ?>

 <form method="post" action="#">
 <input id="latitude" name="lat">
  <input id="latitude" name="long">
  <input type="submit" name="sub" value="sub">
     </form>

--- 更新 ---

<script>
    function geoFindMe() {
     var output = document.getElementById("show");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    latitude  = position.coords.latitude;
    longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=20&size=300x300&sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating...</p>";
  fillLatitudeLongitudeElements();
  navigator.geolocation.getCurrentPosition(success, error);
}

function fillLatitudeLongitudeElements(){
  document.getElementById("latitude").value = latitude;
    document.getElementById("longitude").value = longitude;
}

function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
            case "always":
            return callback(true);
            case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
    window.gBrowser.selectedBrowser,
    "geolocation",
    message,
    "geo-notification-icon",
    {
        label: "Share Location",
        accessKey: "S",
        callback: function(notification) {
            done = true;
            callback(true);
        }
    }, [
    {
        label: "Always Share",
        accessKey: "A",
        callback: remember("always", true)
    },
    {
        label: "Never Share",
        accessKey: "N",
        callback: remember("never", false)
    }
    ], {
        eventCallback: function(event) {
            if (event === "dismissed") {
                if (!done) callback(false);
                done = true;
                window.PopupNotifications.remove(self);
            }
        },
        persistWhileVisible: true
    });
}

prompt(window,
"extensions.foo-addon.allowGeolocation",
"Foo Add-on wants to know your location.",
function callback(allowed) { alert(allowed); });
</script>

 <?php include "../dbconnect.php";

  if(isset($_POST['sub'])){

 $l = $_POST['long'];

 $la = $_POST['lat'];

 $n = $_POST['name'];

  mysql_query("INSERT INTO `gps`(`lat`, `long`, `name`) VALUES ('".$la."','".$l."','".$n."')");

  echo "Done though";

 }
  ?>

<p><button onclick="geoFindMe()">Locate</button></p>
<div id="show"></div>


 <form action="#" method="post">
 <fieldset>
Latitude 6:<br>
<input id="latitude" type="text" name="lat" readonly><br>
Longitude:<br>
<input id="longitude" type="text" name="long" readonly><br><br>
<input onclick="geoFindMe()" type="submit" value="Submit">
 </fieldset>
</form>

已通过添加 ---UPDATED-- 进行编辑

提前谢谢你:)

【问题讨论】:

  • 1.什么意思? 2.每当用户提交表单时,您需要将data插入db吗? 3. 你的insert 块在哪里
  • 你有保存长/纬度的按钮吗?如果是这样,那么您只需将 long/lat 设置为 2 个隐藏变量,然后在帖子中发送。
  • 我已将插入块取出,因为它不起作用。我试图将经度和纬度插入数据库。我试图将数据提取到两个不同的 div 中,但不是 int db
  • @RichardHousham 那是我没试过的东西,现在试试吧:)
  • 我已经更新了,但还是有问题

标签: javascript php mysql database gps


【解决方案1】:

检查这个: send javaScript variable to php variable

您可以创建带有 2 个参数的新 php 文件,然后将该数据插入数据库,然后调用该页面。

下面是 php 文件的格式:

$lat = $_GET['lat'];
$lon = $_GET['lon'];

$insert = "insert into `table_name` (lat, lon) values ('$lat', '$lon')";
//some sql to run the query
if(inserted())
    echo 'done';
else
    echo 'failed';
//just for testing
function inserted(){
    return true;
}

那么当他设置他的位置时,您需要从客户端的浏览器调用这个文件。 这是一个使用 jQuery 的示例:

<script type="text/javascript">
    //make a get call to add.php
    function addToDB(lat, lon) {
        $.get('path_php_file/file.php?lat=' + lat + '&lon=' + lon, function(data) {
            //data refers to the response
            //check if the response == done
            if(data == 'done')
                alert('done!');
            else
                alert('failed!');
        });
    }
    //call the function when user sets his location
    addToDB(1, 2);
</script>

希望对您有所帮助!

【讨论】:

  • 它不需要将它添加到 url 虽然我只需要知道如何获取 javascript 变量并将其放入 mysql 数据库中,如“INSERT INTO tablename”等
  • 您必须先将 JavaScript 变量发送到服务器,然后服务器才能处理该值。
猜你喜欢
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
相关资源
最近更新 更多