在Javascript中使用Ajax检索JSON数据

在Javascript中使用Ajax检索JSON数据,javascript,json,ajax,web,Javascript,Json,Ajax,Web,我不认为这是重复,因为我在任何地方都找不到具体的答案。我是JavaScript新手,不知道如何使用Ajax提取JSON信息并将其显示在我的页面上。我知道我做错了什么,因为我对语言理解得不够好 我的JSON如下所示: { "lots" : [ { "name" : "NE Corner HW4 & 41st", "info" : "$2/Hr<br>Monthly Parking Available", "center" : { "lat

我不认为这是重复,因为我在任何地方都找不到具体的答案。我是JavaScript新手,不知道如何使用Ajax提取JSON信息并将其显示在我的页面上。我知道我做错了什么,因为我对语言理解得不够好

我的JSON如下所示:

{ "lots" : [
{
    "name" : "NE Corner HW4 & 41st",
    "info" : "$2/Hr<br>Monthly Parking Available",
    "center" : {
        "lat" : 57.659390,
        "lng" : -127.414754
    },
    "topLeft" : {
        "lat" : 57.659616,
        "lng" : -127.415102
    },
    "bottomRight" : {
        "lat" :57.659208,
        "lng" :-127.414371
    }
}, ...etc
]}
然后我需要在几个功能中使用这些信息:

for (var i = 0; i < jsonFile.lots.length; i++) {
  marker = new google.maps.Marker({
  position: new google.maps.LatLng(jsonFile.lots[i].center.lat, jsonFile.lots[i].center.lng)
  marker.setMap(map);
}
for(var i=0;i

我做错了什么(除了一切)?这是我的JSON数组吗?我需要解析或字符串化它吗?可能是Ajax调用。Javascript?我觉得它可能是一切。谢谢你的帮助!

为了处理你得到的响应,你必须成功。例如

$.ajax({
    url: 'Your service url',
    type: 'GET' or 'POST',
    dataType: 'json',
    success: function(response){
         //Do what ever you want with the response variable
         //Do a console.log(response) to see what is coming as the response
    }
})
根据您的示例,您可以使用以下内容

jsonFile.done(function(response){
    //Do what ever your want with the response.
})

当您试图使用数据时,数据可能不存在。每个ajax调用都是异步的。 试试这个:

$.get("file_path_here").done(
    function(data){
//do your staff here, data variable contains the json
    }
);

最好改用回调,因为这样不会阻塞。JQuery还有一个getJSON函数,它将Ajax调用返回的字符串解码为JSON,并使用th JSON对象作为参数调用回调

$.getJSON('http://localhost/data.json', function(data){
    for (var i = 0; i < data.lots.length; i++)
        marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lots[i].center.lat, jsonFile.lots[i].center.lng)
        marker.setMap(map);
        });
}
$.getJSON('http://localhost/data.json,函数(数据){
对于(变量i=0;i

请参见

提问前您应该检查,因为它的选项比您的答案多。谢谢,我的Ajax调用现在已修复。我缺少的主要部分是jsonFile.done(function(dataHere){})部分。现在我遇到了另一个由google maps API引起的问题,我将在其他地方发布。
$.getJSON('http://localhost/data.json', function(data){
    for (var i = 0; i < data.lots.length; i++)
        marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lots[i].center.lat, jsonFile.lots[i].center.lng)
        marker.setMap(map);
        });
}
$.ajax({
    url: 'Your service url',
    type: 'GET',
    dataType: 'json',
    url: "filepath/filename.json",
    success: function(data){
        console.log(data);
     }
})