通过JavaScript计算以形成隐藏输入并将其POST到另一页面

时间:2014-07-22 14:39:35

标签: javascript google-maps

我在将Javascript计算(距离和谷歌的旅行时间)传递给隐藏输入方面存在问题。使用onSubmit,我可以在下一页使用它)。特殊性(mi和time_teken)。 在同一页面上使用内部html显示此值根本没有问题。一切正常。 正如你所看到我也使用类似的脚本传递lon和lat值(这不是为了使提交的代码更短,也没有问题。但是对于这些我在改变方法上使用的值。我尝试了很多不同的方法但是在这一点上,我完全失去了。

我会提供一些帮助。

非常感谢你。

    <script language="javascript" type="text/javascript">window.onload=function(){initialize(51.508515, -0.12548719999995228);}</script>

<input type="hidden" value="1.5" id="more_then" name="more_then"/>
<input type="hidden" value="0" id="less_then" />
<script language="javascript">
 function get_distance(form){
     from = form.postcode1.value;
     to = form.postcode2.value;
     calcRoute(from,to);

 }
</script>

<form id="booking" name="booking"  action="test5.php" method='post' onsubmit='get_distance(this.form);'>
<input type="text" name="postcode1" id="postcode1" class="input-postcode1" onChange="Geocode1()" placeholder='Postcode or Town' /></td>
<input type="text" name="postcode2" id="postcode2" class="input-postcode1" onChange="Geocode2()" placeholder='Postcode or Town'/></td>
 <input name="lat1" type="hidden" id="lat1">
<input name="lon1" type="hidden" id="lon1">
 <input name="lat2" type="hidden" id="lat2">
<input name="lon2" type="hidden" id="lon2">
<input name="distance2" type="hidden" id="distance2">
<input name="timetaken" type="hidden" id="timetaken">
<input type="hidden" value="7" name="map_zoom" id="map_zoom"/>
<input type="hidden" value="£" id="curr_format"/>
<input type='submit' name='submit' id='submit' value='Calculate' class='LMV-callback'  >
</form>


<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

<script type="text/javascript">
var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  function initialize(lat,lng) {
    directionsDisplay = new google.maps.DirectionsRenderer();
    //var location = new google.maps.LatLng(9.93123, 76.26730);
    var location = new google.maps.LatLng(lat, lng);
    var zm =  parseInt(document.getElementById('map_zoom').value);
    var myOptions = {
      zoom: zm,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: location
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);

}

  function calcRoute(from,to){
    var start = from;
    var end = to;
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC     //IMPERIAL     //METRIC
    };
    // function to round the decimal digits eg: round(123.456,2); gives 123.45
    function round(number,X) {
        X = (!X ? 2 : X);
        return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
    }

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        var distance = response.routes[0].legs[0].distance.text;
        var time_taken = response.routes[0].legs[0].duration.text;
        var calc_distance = response.routes[0].legs[0].distance.value;
        var less_then =  document.getElementById('less_then').value;
        var more_then =  document.getElementById('more_then').value;
        var curr_format =  document.getElementById('curr_format').value;

                if (calc_distance <= 16510) {
                    var amount_to_pay = calc_distance * less_then;
                }
                else {
                    var amount_to_pay = (calc_distance-16510) * more_then;
                }

    function roundNumber(numbr,decimalPlaces) 
    {
        var placeSetter = Math.pow(10, decimalPlaces);
        numbr = Math.round(numbr * placeSetter) / placeSetter;
        return numbr;
    }
    var mi =  calc_distance / 1.609;
    var mi = mi/1000;
    var mi = roundNumber(mi, 2);   //Sets value to 2 decimal places.

/// my problem might by here

    document.getElementById("distance2").value = mi;
    $("#distance2").val(mi);
    document.getElementById("timetaken").value = time_taken;
    $("#timetaken").val(time_taken);



                var rounded_amount_to_pay = round(amount_to_pay/1000,2); 

        document.getElementById('distance').innerHTML = '<div class="distance-inner"><span>'+ "The distance between <em>"+from+"</em> and <em>"+to+"</em>: <strong> "+mi+ " mi</strong>\n\
                <br/>\n\
                Time take to travel: <strong>"+time_taken+"</strong><br/>\n\
                </span></div>";

            var steps = "<ul>";
        var myRoute = response.routes[0].legs[0];
        for (var i = 0; i < myRoute.steps.length; i++) {
         steps += "<li>" + myRoute.steps[i].instructions + "</li>";
        }
        steps += "</ul>";
        document.getElementById('steps').innerHTML = '<div class="steps-inner"><h2>Driving directions to '+response.routes[0].legs[0].end_address+'</h2>'+steps+'</div>';
      }
      else{
        document.getElementById('distance').innerHTML = '<span class="gdc-error">Google Map could not be created for the entered parameters. Please be specific while providing the destination location.</span>';
      }
    });

  }

//window.onload=function(){initialize();}// JavaScript Document

</script>

3 个答案:

答案 0 :(得分:0)

似乎正在发生的事情是,您在action="test5.php"上执行submit并尝试侦听事件的同一表单上有asynchronous。由于获取路径数据是一个directionsService.route(request, function(response, status) {...进程,这意味着它可以在将来任何不加选择的时间返回一个值,因此您无法立即获取这些值。它们仅在function(response, status){...返回后设置,并且内联匿名函数test5.php运行。此时,您的表单会将自己提交到change页面,因此您的值为空。

您说您在submit事件发生后立即成功设置的其他值,因此会在submitted之前包含在表单中。

我建议使用AJAX提交表单或添加支票以查看表单之前是否为return false,如果没有,请阻止通过javascript return true {{3然后当你从调用googles API中返回值时,你可以通过javascript强制另一次提交,但是这次{{1}}如果你已经确认数据是隐藏的输入中那么。

答案 1 :(得分:0)

document.booking.elements['distance'].value = mi;
document.booking.elements['timetaken'].value = time_taken;

答案 2 :(得分:-1)

试试这个:

var lat = document.getElementById("lat1").value;

var lat = document.booking.elements['lat1'].value;