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

Posted

技术标签:

【中文标题】如何将此 JavaScript <div> 数据自动填充到 PHP 表单中?【英文标题】:How can I populate this JavaScript <div> data automatically to a PHP Form? 【发布时间】:2011-12-03 09:09:09 【问题描述】:

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

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

【问题讨论】:

【参考方案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 脚本中。

如果有帮助请告诉我!

【讨论】:

当你说“并在你的代码上添加这个”我应该在哪里添加这个?我尝试了 main.js 的几个地方都没有运气【参考方案2】:

为您的表单输入命名,然后使用您的 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>

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

【讨论】:

以上是关于如何将此 JavaScript <div> 数据自动填充到 PHP 表单中?的主要内容,如果未能解决你的问题,请参考以下文章

如何将此特定行的 div css 行转换为 django 模板行?

如何在使用javascript粘贴之前修改复制的文本

怎么使用javascript动态生成嵌套的div

在javascript中选择第一个div孩子的第二个孩子[重复]

如何将两个单独的 javascript 合并为一个?

javascript innerHTML累加值问题~~求解