来自jquery帖子的未定义结果

时间:2013-07-07 21:32:25

标签: jquery

我对ajax比较陌生,并且看了很多其他线程但找不到答案。

我正在尝试从.post调用中读取结果但是不成功。

以下是代码:

$.post( http://www.mapquest.com/directions/v1/routematrix?key=...,//I have my actual key where the three dots are
    {locations:[{latLng:{lat:54.0484068,lng:-2.7990345}},{latLng:{lat:53.9593817,lng:-1.0814175}},{latLng:{lat:53.9593817,lng:-1.0514175}},{latLng:{lat:53.9593817,lng:-1.0114175}}]},
    function (data, status, xhr) {
        console.log(typeof(data)); //this shows: object
        console.log(data); //this shows: [object object]
        console.log(data[0]); //this shows: undefined
        console.log(data.length); //this shows: undefined
        console.log(status); //this shows: success          
    }, 
    'json'
);

我期待输出看起来像这样:

{
   allToAll: false,
   distance: [
      0,
      25.685,
      107.846,
      78.452
   ],
   time: [
      0,
      2260,
      7253,
      5930
   ],
   locations: [
      "Lancaster, England",
      "Liverpool, England",
      "Chester, England",
      "Stoke-on-Trent, England"
   ],
   info: {
      ...
   }
}         

知道我做错了吗?

2 个答案:

答案 0 :(得分:0)

您的问题是您尝试记录数据的方式。您已在data中拥有javascript对象,因此您可以直接访问这些属性:

console.log(typeof(data)); // object - correct
console.log(data);         // [object object]  - correct
console.log(data[0]);      // undefined - correct; this is not an array
console.log(data.length);  // undefined - correct; not an array, so no length
console.log(status);       // success          

尝试直接记录属性。例如:

console.log(data.locations[0]); // Should be 'Lancaster, England'
console.log(data.distance[1];   // should be 25.685
console.log(data.time[3]);      // should be 5930  

答案 1 :(得分:0)

如果有人感兴趣,我通过使用get方法(而不是post)并在URL中添加JSON来规避问题:

var matrixUrl3 = 'http://www.mapquestapi.com/directions/v1/routematrix?key=YOUR_KEY_HERE&json={locations:[{latLng:{lat:54.0484068,lng:-2.7990345}},{latLng:{lat:53.9593817,lng:-1.0814175}},{latLng:{lat:53.9593817,lng:-1.0514175}},{latLng:{lat:53.9593817,lng:-1.0114175}}]}';

$.get(newURL,function(data, status, xhr) {                         
            //console here
        }, 'json');

不确定为什么post方法不起作用,尝试按照此处的说明对我的JSON进行字符串化: http://www.json.org/js.html 但也没有帮助。 无论如何,如上所述绕过这个问题就像一个魅力!