簡體   English   中英

了解如何使用 jQuery 解析 JSON

[英]Understanding how to Parse JSON with jQuery

我很欣賞這方面的很多帖子,還有很多關於谷歌的帖子,但我很難理解如何分解 JSON stream 並訪問數據。

我有一個簡單的 JSON 響應:

{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [-122.4211908, 37.7564513]},
"properties": {
"id": "2950648771574984913",
"accuracyInMeters": 80,
"timeStamp": 1309323032,
"reverseGeocode": "San Francisco, CA, USA",
"photoUrl": "https://www.google.com/latitude/apps/badge/api?type=photo&photo=uuRL2jABAAA.9fWeRzNpS-tdX0cqHxxclg.7zdBNW-Rb634EIkOgyO8sw",
"photoWidth": 96,
"photoHeight": 96,
"placardUrl": "https://www.google.com/latitude/apps/badge/api?type=photo_placard&photo=uuRL2jABAAA.9fWeRzNpS-tdX0cqHxxclg.7zdBNW-Rb634EIkOgyO8sw&moving=true&stale=true&lod=1&format=png",
"placardWidth": 56,
"placardHeight": 59
}
}
]
}

我正在嘗試訪問其中的所有數據,例如:

兩個坐標。 反向地理編碼。 等等

我已經像這樣構建了一個 function:

    function findTristan(){
            var FindUrl = "/proxy.php";

            var tristanData = $.getJSON(FindUrl,function(json){});

            // this is the part I have failed to get right.
            alert(tristanData.coordinates);

    }

由於 AJAX 的異步特性,您只需要在成功回調中操作數據,因為這是該數據可用的唯一位置。 $.getJSON function 立即返回,它不返回 AJAX 請求的結果。 因此,應使用您在代碼中留空的匿名回調:

function findTristan() {
    var FindUrl = '/proxy.php';
    $.getJSON(FindUrl, function(json) {
        var lat = json.features[0].geometry.coordinates[0];
        var lon = json.features[0].geometry.coordinates[1];
        alert('lat: ' + lat + ', lon: ' + lon);
    });
}

You need to use the $.parseJSON function to transform your JSON into a js array: http://api.jquery.com/jQuery.parseJSON/

問候,

最大限度

這兩個應該在你的getJSON完整 function 中使用。

json.features[0].geometry.coordinates[0]
json.features[0].geometry.coordinates[1]

在發出 Ajax 請求后,您不應該只發出alert 為什么? 因為 Ajax 調用本質上是異步的。 這僅僅意味着請求被發送出去,您的代碼會立即繼續執行,而無需等待請求得到響應。 這就是為什么在您從服務器返回結果之前執行alert (當然沒有任何結果)的原因。

而且getJSON也不會按照您的方式返回數據。 它將在其完整的 function 中返回數據,您必須自己使用它。

function findTristan(){
    var FindUrl = "/proxy.php";

    var tristanCoords = {};

    $.getJSON(FindUrl, function(data){

        tristanCoords = data.features[0].geometry.coordinates;
        alert("x: " + tristanCoords[0] + ", y: " + tristanCoords[1]);

    });
}

建議

每當您必須使用 javascript、對象等時,請使用Firebug (Firefox 插件)並調試您的代碼。 您將能夠深入了解您的 object 並准確查看其結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM