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

时间:2011-10-08 00:00:37

标签: php javascript mysql forms geolocation

我有一个.js,用经度和纬度数据填充2 <div>,并且它的工作正常。但我希望获取该数据并使用它填充表单,以便我们可以在提交时将其捕获到我的数据库中。我不关心表单是否隐藏或可见,我只需要在页面加载时脚本显示数据,它也会自动放在表单中。任何帮助是极大的赞赏。谢谢。

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);

2 个答案:

答案 0 :(得分:1)

为表单输入命名,然后用你的JS选择它们:

 <form action='#' method='post'>
 <input type='hidden' id='hidden1' name='hidden1' value=''/>
 <input type='text' id='text1' name='text1' value='text'/>
 </form>

 <script>
      //Add this code into whatever javascript you want to populate the form
      var thisElem = document.getElementById("hidden1");
      thisElem.value = yourOtherJavascriptValue;
 </script>

如果您不希望用户看到此信息,请使用多个隐藏元素,否则请使用文本

答案 1 :(得分:1)

将此表单放在您的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脚本。

让我知道它是否有帮助!