Newb 在查询谷歌地图以了解两个城市之间的距离的简单任务时遇到了麻烦。真的,这是获取 JSON 数据并加以利用的第一次学习尝试。
我用谷歌搜索了很多,并首先在 SO 上阅读了许多相关答案。(虽然我最终在这里找到了主要答案。)
我粘贴了所有代码,以及关于我在想什么的评论,希望有人能用初学者的方式解释我所缺少的东西。
主要问题是我使用我尝试过的两种方法之一获取数据($.ajax,但不是 $.getJSON,虽然我认为两者都可以),请参阅代码末尾的控制台输出,但是我无法弄清楚如何实际获取/使用数据。具体来说,在多嵌套对象/数组组合中,我试图在返回的“responseText”中的“routes”中的“legs”中的“distance”中获取“text”。
[编辑:]好的,我终于找到了一个现有的 SO 问题,这[足以弄清楚](如何使用 jquery 或 javascript 获取 JSON 中的对象)
事后看来,我应该一直在寻找更多现有的答案。
我不确定是要离开、删除还是擦除,但我会稍微编辑一下并暂时离开,因为问题的某些部分仍然令人困惑,包括:
- 如何在下面的代码中使用 $.getJSON —— 那也不应该有效吗?
- 如何准确地知道将整个 JSON 对象的哪一部分用作 $.parseJSON() 方法中的参数;
如果您可以看到输出的对象,为什么您仍然必须使用 $.parseJSON,并且它看起来已经像对象/数组组合了。请参阅下面的评论。
<!DOCTYPE html> <html> <head> <title>City Distances</title> <script src="js/jquery.min.js"></script> </head> <body> <input type="text" id="city1" value="Atlanta"><br/> <input type="text" id="city2" value="Orlando"><br/> <button type="submit" id="btn">Submit</button> <script> var city1 = document.getElementById('city1'); var city2 = document.getElementById('city2'); var btn = document.getElementById('btn'); var valCities = []; function getCities () { valCities[0] = city1.value; valCities[1] = city2.value; var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false"; // I'm confused about what $.getJSON is supposed to get. // Here's why I was trying to get the JSON data. I never saw how this would work; no idea. var b = $.getJSON(gMap); // Is the data I'm looking for in here, somewhere? // I thought there'd be something like the c['responseText'], below. // (I numbered each element (g), b/c I thought I could access with [#] bracket notation). var g = 0; for (var i in b) { console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]); g += 1; }; // jQuery method (I found more examples that used this method, so I tried this, too.) // I'm confused by the example showing the argument 'json' being passed in, b/c I didn't // use it. // But c['responseText'] seemed to have the "distance" data I needed. var c = $.ajax({ type: "GET", url: gMap, dataType: "json", success: function(json) { // I'm trying to see what was gotten. Added counter for the elements; I // thought maybe I could access with bracket notation using the number of // the element. // The relevant output is listed, below, in comment at end of script. console.log("\n $.ajax success: \n") var h = 0; for (var j in c) { console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]); h += 1; }
**这就是最终奏效的**
// nested objects and arrays...
var d = c['responseText'];
var jsonObject = $.parseJSON(d);
var theDistance = jsonObject.routes[0].legs[0].distance.text;
console.log("*** theDistance: " + theDistance + "\n\n ***");
还是我应该像这样使用 .map ?
不管怎样,剩下的就在这里,主要是为了最后的 console.log 输出:
// **And if this works, and prints out all the data:
var d = c['responseText']; // (from above)
console.log("ddd: " + d);
/* This is what it prints to the console:
ddd: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "442 mi",
"value" : 710661
},
*/
// **Then why doesn't this work? (It says routes is undefined.)
console.log(d.routes[0].legs[0].distance.text);
}
});
}
// Event handler for the little form (which already has the two demo cities, pre-populated.
btn.addEventListener("click", getCities, false);
/*
** OUTPUT **
This is the relevant JSON data returned from Google from the console.log, above.
[Console output:]
. . .
$.ajax: <18> c[responseText]: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
** --- This is what I was trying to get --- **
**"text" : "442 mi",**
"value" : 710661
},
"duration" : {
"text" : "6 hours 13 mins",
"value" : 22360
},
"end_address" : "Orlando, FL, USA",
"end_location" : {
"lat" : 28.53831440,
"lng" : -81.37924350
},
"start_address" : "Atlanta, GA, USA",
"start_location" : {
"lat" : 33.74883970,
"lng" : -84.38750639999999
*/
</script>
</body>
</html>