Как передать данные JavaScript на другую страницу? - PullRequest
0 голосов
/ 02 марта 2019

У меня есть такой код:

<input type="text" id="start" name="o">
<input type="text" id="end" name="d">
<input type="text" id="total" name="total" hidden="hidden">

<button onclick="calcRoute();" value="/index.php?route=information/mymove" >text</button>

<script>
      function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var request = {
          origin: start,
          destination: end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            computeTotalDistance(response);
          } 
        });
      }
      function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000.
      document.getElementById("total").value = total + " km";
      }
</script>

Если я использую этот код для кнопки:

<input type="button" value="go" onclick="calcRoute();">, это выполняет функцию javascript, но не передает данные другомустр.

У меня также есть эта часть в файле контроллера:

if (isset($this->request->post['o'])) {
            $data['o'] = $this->request->post['o'];
        }

        if (isset($this->request->post['d'])) {
            $data['d'] = $this->request->post['d'];
        }

        if (isset($this->request->post['total'])) {
            $data['total'] = $this->request->post['total'];
        }

Ответы [ 2 ]

0 голосов
/ 02 марта 2019

Несколько важных вещей: вам нужно сделать эту кнопку правильной кнопкой отправки, вам нужно убедиться, что она возвращает обратный вызов, а не вызов функции напрямую, и вам нужно убедиться, что обратный вызов возвращает ложь.Это как предотвратить поведение по умолчанию, при котором форма отправлялась бы без запуска скрипта.

<form action="index.php?route=information/mymove" method="post">
    <input type="text" id="start" name="o">
    <input type="text" id="end" name="d">
    <input type="text" id="total" name="total" hidden="hidden">        
    <button type="submit" onclick="return calcRoute();">text</button>
</form>

<script>
      function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var request = {
          origin: start,
          destination: end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            computeTotalDistance(response);
          } 
        });
        return false;
      }
      function computeTotalDistance(result) {
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
      }
      total = total / 1000.
      document.getElementById("total").value = total + " km";
      }
</script>
0 голосов
/ 02 марта 2019

Думаю, вы сможете изменить функцию computeTotalDistance, чтобы после завершения всех вычислений она добавляла общее значение к требуемому скрытому входу и затем отправляла форму.

function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
    }
    total = total / 1000;
    document.getElementById("total").value = total + " km";

    if( total && document.getElementById("total").value!='' ) document.getElementById("total").parentNode.submit();
}

В качестве альтернативы другой вариант будет использовать эту же функцию обратного вызова для отправки и ajax-запроса на тот же URL-адрес конечной точки.

function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
    }
    total = total / 1000;
    document.getElementById("total").value = total + " km";

    /* send the total by ajax to endpoint url */
    ajax.call( this, url, 'total='+total, (r)=>{
        alert(r);
    } );
}


function ajax( url, params, callback ){
    with( new XMLHttpRequest() ){
        onreadystatechange=function(e){
            if( this.status==200 && this.readyState==4 ){
                callback.call( this.response )
            }
        }
        open( 'POST', url, true );
        setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        send( params );
    }
}

Первоначально не указывалось, что вы хотите view итого на другой странице, просто вы хотите отправить значение на другую страницу.Поскольку это требование, ajax, в данном случае, вовсе не лучший вариант - поскольку существует форма, которую следует отправить, как пытается сделать моя изначально измененная функция.

обновление: Полный пример, проверенный и работающий, имитирующий то, что пытается сделать ваш код.

<code><?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        /* 
            consider this as "another page" - the form has submitted to here
            and you can see the POST data...
        */
        exit(printf('<pre>%s
', print_r ($ _ POST, true)));}?> Карты Google: расчеты маршрутов function initMap () {let _lat = 56.55;пусть _lng = -2,72;let _form = document.querySelector ('form [name = "route-plotter"]');let latlng = new google.maps.LatLng (_lat, _lng);let options = {zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.TERRAIN};let map = new google.maps.Map (document.getElementById ('map'), options);const calcroute = function () {let request = {origin: document.getElementById ('start'). value, destination: document.getElementById ('end'). value, travelMode: google.maps.DirectionsTravelMode.DRIVING};let directionsService = new google.maps.DirectionsService ();let directionsDisplay = new google.maps.DirectionsRenderer ();directionsService.route (запрос, функция (ответ, статус) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections (response); рассчитанное сопротивление (response);}});};const рассчитанное сопротивление = функция (результат) {пусть всего = 0;let route = result.routes [0];route.legs.forEach (leg => {total + = leg.distance.value;});. Document.getElementById ( 'всего') значение = общая;_form.submit ();};_form.querySelector ('button'). addEventListener ('click', calcroute, false)}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...