【问题标题】:JavaScript to PHP arrayJavaScript 到 PHP 数组
【发布时间】:2014-03-30 16:58:38
【问题描述】:

我正在尝试将 javascript 对象转换为 php 数组。

我想在 php 脚本中使用 results[j].distance.textresults[j].duratio.text。我正在使用 Google 的 API 来获取经度和纬度的持续时间和距离。

但是如何将这些客户端数据发送到服务器端(PHP)?

我想我需要进行 AJAX 调用,但我不知道该怎么做。

希望你们能帮帮我。谢谢。

我的代码如下:

var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>);
var destinationA = 'Min adresse, Aarhus';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

function initialize() {
  var opts = {
    center: new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>),
    zoom: 10
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
}

window.onload = function calculateDistances(){
    var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1],
      destinations: [destinationA],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
};


function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        outputDiv.innerHTML += origins[i] + ' til ' + destinations[j]
            + ': ' + results[j].distance.text + ' tid til destination '
            + results[j].duration.text + '<br>';
      }
    }
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

【问题讨论】:

    标签: javascript php ajax json google-maps-api-3


    【解决方案1】:

    您必须进行 AJAX 调用。

    我建议你看看 jQuery。它为您提供了一个易于理解的 AJAX 工作方式实现,还帮助您处理响应。 (成功、错误等)

    它提供了一个很好的清晰语法,例如:

    $.ajax({
    url:"handlePage.php",
    data:{json object here},
    dataType:"json",
    success:function(jd){
         console.log("SUCCESS");   
    }});
    

    您可以在此处阅读更多信息:

    jQuery Ajax Page

    在 PHP 和 JavaScript 之间进行数据通信的最佳方式是使用 JSON。

    JavaScript 对象可以呈现为 JSON 对象。 PHP 包含将这些对象解码为数组的功能。

    JSON Tutorial

    要让 PHP 对此进行解码,您必须查看 PHP 的 json_decode() 和 json_encode() 函数:

    PHP: json_encode manual PHP: json_decode manual

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      我没有看过你的完整代码,但可以通过以下步骤来回答:

      • 在提交时,创建一个字符串数组,用逗号分隔。
      • 在服务器端以逗号分隔字符串,你有你的 php 数组

      示例:

      <input name="tb1" class="testCreate" value="v1" />
      <input name="tb2" class="testCreate" value="v2" />
      
      <script>
        var result = $('.testCreate').map(function() {return this.value;}).get().join(',');
      
        $.ajax({
              url: "Path/to/file",
              type: "POST",
              cache: false,
              data: "value=" + result,
              success: function (html) {
                  //Do somehting when done
              }
          });
      </script>
      

      和服务器端获取:

      <?php
      $array = implode(",", $_POST["value"]);
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-09
        • 1970-01-01
        • 1970-01-01
        • 2013-03-07
        • 2013-04-06
        • 2015-10-06
        • 2013-09-18
        • 2011-01-17
        相关资源
        最近更新 更多