php - 如何将此 JavaScript <div> 数据自动填充到 PHP 表单?

标签 php javascript mysql forms geolocation

我有一个填充 2 <div> 的 .js的经度和纬度数据及其完美的工作。但是我想获取这些数据并用它填充一个表单,这样我就可以在他们点击提交时将它捕获到我的数据库中。我不在乎表单是隐藏的还是可见的我只需要在页面加载并且脚本显示数据时它也会自动放置在表单中。任何帮助是极大的赞赏。谢谢。

该 js 称为 main.js,从下面找到,代码用于填充 页面上的数据是:

    <section>
<ul>
               <dl>
                       <dt>Latitude:</dt>
                       <dd id="latitude">Please...</dd>
               </dl>
               <dl>
                       <dt>Longitude:</dt>
                       <dd id="longitude">Wait...</dd>
               </dl>
               <dl>
                       <dt>Accuracy:</dt>
                       <dd id="accuracy">While...</dd>
               </dl>
               <dl>
                       <dt>Timestamp:</dt><dd id="timestamp">Calculating...</dd>
               </dl>
</ul>           
</section>



    <!--Now  and this is my issue I need the <dd id="latitude"> and <dd id="longitude"> some how in
a form to get in a SQL database -->




<ul class="pageitem">
                       <li class="smallfield"><span class="name">latitude</span><input
placeholder="" id="latitude" name="latitude" type="num" />
                       </li></ul>
<ul class="pageitem">
                       <li class="smallfield"><span class="name">Longitude</span><input
placeholder="" id="longitude" name="longitude" type="num" />
                       </li></ul>

到目前为止我找到的最好的文档是: How do I collect data from a div to use in a form

但我无法让它工作。提前谢谢大家。

我使用的 JavaScript 是:

/*
 * 
 * Find more about this app by visiting
 * http://miniapps.co.uk/
 *
 * Copyright (c) 2010 Alex Gibson, http://miniapps.co.uk/
 * Released under MIT license
 * http://miniapps.co.uk/license/
 * 
 */

var geoUtilityApp = (function() {

    var updateLocation = null;

    return {

        //initializes watchPosition.
        init: function () {

            updateLocation = navigator.geolocation.watchPosition(geoUtilityApp.success, geoUtilityApp.fail, {enableHighAccuracy: true});

        },

        success: function (position) {

            var timeStamp = null,
            heading = null,
            accuracy = null,
            altAccuracy = null,
            speed = null;


            //we must check to see whether or not each piece of data has been returned in the success call.
            //if a piece of data has been returned, we then update the meter readout.

            if(!position.coords.latitude) {
                document.querySelector('#latitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#latitude').innerHTML = position.coords.latitude;
            }

            if(!position.coords.longitude) {
                document.querySelector('#longitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#longitude').innerHTML = position.coords.longitude;
            }

            if(!position.coords.accuracy) {
                document.querySelector('#accuracy').innerHTML = 'Calculating';
            }
            else {
                accuracy = Math.round(position.coords.accuracy);
                document.querySelector('#accuracy').innerHTML = accuracy + ' meters';
            }

            if(!position.timestamp) {
                document.querySelector('#timestamp').innerHTML = 'Calculating';
            }
            else {
                //convert timestamp to be more human readable.
                timeStamp = geoUtilityApp.formatTimeStamp(position.timestamp);
                document.querySelector('#timestamp').innerHTML = timeStamp;
            }

            //update 'map' button href.
            geoUtilityApp.setMapURL(position.coords.latitude, position.coords.longitude);

            //update 'Mail location info' button href.
            geoUtilityApp.updateMail(position.coords.latitude, position.coords.longitude, accuracy, position.coords.altitude, altAccuracy, speed, heading, timeStamp);

        },

        //called if watchPosition returns an error.
        fail: function(error) {

            switch(error.code) {
                case 0:
                    // unknown error alert error message
                    alert('An unknown error occured');
                    break;

                case 1:
                    // permission denied alert error message
                    alert('Permission denied by user');
                    break;

                case 2:
                    // position unavailable error message
                    alert('Position unavailable');
                    break;

                case 3:
                    // timeout error message
                    alert('The request timed out');
                    break;
            }
        },


        //function that stops watchPosition, if we wished to call it
        stop: function() {

            navigator.geolocation.clearWatch(updateLocation);
        },

        //updates the href of the 'Map' button.
        setMapURL: function(latitude, longitude) {

            var URL = 'http://maps.google.com/maps?q=' + latitude + ',' + longitude;

            document.querySelector('#map').onclick = function() {
                window.open(URL);   
            };
        },

        //updates the href of the 'Mail location info' button.
        updateMail: function(latitude, longitude, accuracy, timeStamp) {

            (!latitude) ? latitude = '?' : latitude = latitude;
            (!longitude) ? longitude = '?' : longitude = longitude;
            (!accuracy) ? accuracy = '?\n' : accuracy += ' meters\n';
            (!timeStamp) ?timeStamp = '?\n\n' : timeStamp += '\n\n';

            var subject = 'My location';
            var body = 'Latitude: ' + latitude + '\nLongitude: ' + longitude + '\nAccuracy: ' + accuracy + 'Timestamp: ' + timeStamp + 'http://maps.google.com/maps?q=' + latitude + ',' + longitude + '\n';

            document.querySelector('#maillink').href = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
        },

        //toggles the large 'Mail location info' button.
        sendMail: function() {

            var mailLink = document.querySelector('#maillist');

            if (mailLink.style.display === 'none') {
                mailLink.style.display = 'block';
            }
            else {
                mailLink.style.display = 'none';
            }
        },

        //takes a variable that is degrees clockwise from true north and returns the relevant compass direction.


        //takes a Unix timestamp and returns a formatted, human readable timestamp.
        formatTimeStamp: function(timestamp) {

            var date = new Date(timestamp);

            var month = date.getUTCMonth() + 1,
            day = date.getUTCDate(),
            year = date.getUTCFullYear(),
            hours = date.getUTCHours() - 5,
            minutes = date.getUTCMinutes(),
            seconds = date.getUTCSeconds(),

            formattedTime =  year + '-' + month + '-' + day + ' T ' + hours + ':' + minutes + ':' + seconds;

            return formattedTime;
        },

        loaded : function() {

            //test to see if browser supports geo location api.
            if (window.navigator.geolocation) { 

                //hide the address bar if visible.
                window.scrollTo(0,0);

                //hack to enable active pseudo selectors on buttons in mobile webkit
                document.addEventListener("touchstart", function() {},false);

                //hide the mail list items button.
                document.querySelector('#maillist').style.display = 'none';

                //initialise the app.   
                geoUtilityApp.init();

                //add an event listener for when the mail button is clicked.
                document.querySelector('#mail').addEventListener('click', geoUtilityApp.sendMail, false);

            } else {  
                alert('Your browser does not support Geolocation API. Sorry!');
            }
        }
    };

}());

window.addEventListener("DOMContentLoaded", geoUtilityApp.loaded, true);

最佳答案

将此表单放在您的 html 代码中的任何位置:

<form action="your_form_destination.php" method="post">
 <input type="hidden" id="long" name="long" />
 <input type="hidden" id="lat" name="lat" />
<input type="submit" value="Save values" />
</form>

然后在您的代码中添加:

       //......
        if(!position.coords.latitude) {
            document.querySelector('#latitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#latitude').innerHTML = position.coords.latitude;
            document.getElementById("lat").value =  position.coords.latitude;
        }

        if(!position.coords.longitude) {
            document.querySelector('#longitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#longitude').innerHTML = position.coords.longitude;
            document.getElementById("long").value =  position.coords.longitude;
        }
      //......

这应该可以解决您的问题,当您单击该按钮时,信息将发布到您的 php 脚本中。

如果有帮助,请告诉我!

关于php - 如何将此 JavaScript <div> 数据自动填充到 PHP 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693910/

相关文章:

php - 限制服务器中上传文件的大小

php - 无法在实时服务器中将 shell_exec 用于 laravel artisan 命令

javascript - 如何在 Plot 中使用 Json 绘制图表?

Mysql搜索匹配和排序

php - 从其他列详细信息获取数据

php - Laravel 5.4 firstOrCreate 或 firstOrNew 如果唯一只是 id

php - 从 mysql_num_rows 选择查询

php - 为什么我无法使用 post 请求使用 jquery 更新数据库中的数据?

javascript - C#和javascript之间的加密结果差异

javascript - 使用 Javascript 或 RegEx 限制数量