如何在laravel 5.1中使用javascript在链接上添加变量

时间:2017-05-01 12:30:51

标签: javascript laravel

是否可以在javaScript上的路由URL上添加变量?我需要将变量传递回控制器。这是我的代码:

<script>
  function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 6,
      center: {lat: 10.103523, lng: 123.640538}
    });
    directionsDisplay.setMap(map);

    document.getElementById('go_submit').addEventListener('click', function() {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    });
  }

  function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    var waypts = [];
    var checkboxArray = document.getElementById('waypoints');
    for (var i = 0; i < checkboxArray.length; i++) {
      if (checkboxArray.options[i].selected) {
        waypts.push({
          location: checkboxArray[i].value,
          stopover: true
        });
      }
    }

    directionsService.route({
      origin: document.getElementById('start').value,
      destination: document.getElementById('complete_add').value,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById('directions-panel');
        summaryPanel.innerHTML = '';

        for (var i = 0; i < route.legs.length; i++) {
          var routeSegment = i + 1;

          summaryPanel.innerHTML += '<input type="text" value="' + parseInt(route.legs[i].distance.text) + ' * 10 = " name="km" id="km">' ;
          summaryPanel.innerHTML += '<input type="text" value="' + parseInt(route.legs[i].distance.text) * 10 + '" name="km" id="km">' ;

          var fee = '';

          $fee = parseInt(route.legs[i].distance.text) * 10;

          summaryPanel.innerHTML += '<a href="{{ url("/mode_of_payment/".' + $fee + ')}}" class="btn btn-success">CONTINUE</a>';


        }
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }
</script>

我不知道该怎么做。

summaryPanel.innerHTML += '<a href="{{ url("/mode_of_payment/".' + $fee + ')}}" class="btn btn-success">CONTINUE</a>';

我想把变量放在路线上。

2 个答案:

答案 0 :(得分:0)

您将无法在JavaScript循环中动态生成PHP代码。你可以做的是将URL保存在一个javascript变量中并使用该变量循环。

var fee = parseInt(route.legs[i].distance.text) * 10;

var custom_location = '{{ url("/mode_of_payment/" }}';

summaryPanel.innerHTML += "<a href='" + custom_location + "/" + fee + "' class='btn btn-success'>CONTINUE</a>"; 

答案 1 :(得分:0)

我认为您想要附加根网址。为此,您只需声明一个变量

root_url = "<?php echo Request::root(); ?>";

然后您可以直接在脚本代码中使用此变量。然后你的代码将

summaryPanel.innerHTML += '<a href="'+root_url+'/mode_of_payment/'+fee+'" class="btn btn-success">CONTINUE</a>';