【问题标题】:Accessing elements in an array in JavaScript (array returned from PHP)在 JavaScript 中访问数组中的元素(从 PHP 返回的数组)
【发布时间】:2017-05-03 01:08:45
【问题描述】:

我目前正在从事一个项目,该项目通过 JQuery 调用从 Google Maps API 中提取数据,在 PHP 中对其进行处理,然后最终将结果显示在地图中。我目前能够将 API 调用中的元素放入数组并将数组发回,但我不确定如何再次访问我的 JavaScript 中的特定数组。作为参考,第一个子数组是搜索位置的经度和纬度,其余子数组是搜索位置周围目的地的经度、纬度和名称。我想知道你们中是否有人知道我可以如何访问这些元素(或者可能是一种不同的方式以一种更易于访问的方式从 PHP 发送回它们)。我的 javascript 调用是:

    function getPlace() {
    var address1 = $("#address1").val();
    var city1 = $("#city1").val();
    var state1 = $("#state1").val();
    var type = $("#placesList").val();
    var lat; var long;
     $.ajax({
        url: 'findPlace.php',
        type: 'GET',
        data: {address1: address1, city1: city1, state1: state1, type: type},
        success: function(stuff) {
            var info = JSON.parse(stuff);
            lat = info.lat;
            long = info[0].long;
            var name = info.first();
        },
        error: function(e) {
            console.log(e.message);
        } 
    });
}

我的 PHP 代码 (findPlace.php) 是这样的:

 <?php
$type = $_GET["type"];
$address1 = $_GET["address1"];
$city1 = $_GET["city1"];
$state1 = $_GET["state1"];

$key = "AIzaSyBubKVVsy-AjrJoS57GWMskC8vkr3xsj0g";

// Find the location
$niceStreet = str_replace(" ", "+", $address1);
$niceCity = str_replace(" ","+", $city1);
$niceState = str_replace(" ","+", $state1);
$address = $niceStreet.",+".$niceCity.",+".$niceState;

$jsonURL = "https://maps.googleapis.com/maps/api/geocode/json?address=".$address."&key=".$key;
$json = file_get_contents($jsonURL);
$decodedJSON = json_decode($json, true);

$lat = $decodedJSON["results"][0]["geometry"]["location"]["lat"];
$long = $decodedJSON["results"][0]["geometry"]["location"]["lng"];


// Find the places
$placeURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=".$lat.",".$long."&radius=1000&type=".$type."&key=".$key;
$placeJSON = file_get_contents($placeURL);

$decodedPlace = json_decode($placeJSON, true);

$place = $decodedPlace["results"][0]["name"];
$size = count($decodedPlace["results"]);

$results[0]["lat"] = $lat;
$results[0]["long"] = $long;
for($i = 1; $i < 6; $i++){
    $c = $i - 1;
    $results[$i]["lat"] = $decodedPlace["results"][$c]["geometry"]["location"]["lat"];
    $results[$i]["long"] = $decodedPlace["results"][$c]["geometry"]["location"]["lng"];
    $results[$i]["name"] = $decodedPlace["results"][$c]["name"];
}

echo json_encode($results);

如您所见,我试图访问几个不同数组中的不同变量,但它们都返回 PHP 返回的整个数组,而不是值本身。感谢您的帮助!

【问题讨论】:

    标签: javascript php jquery arrays google-maps


    【解决方案1】:

    从时间戳中可以看出,我很快就找到了这个问题的答案。我只是使用var name = info[1]["name"];之类的代码访问它,我之前使用过这种方法,但我想我只是有语法错误。

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      相关资源
      最近更新 更多