【问题标题】:Retrieving JSON data using Ajax in Javascript在 Javascript 中使用 Ajax 检索 JSON 数据
【发布时间】:2015-07-27 04:32:03
【问题描述】:

我不认为这是重复,因为我在任何地方都找不到具体的答案。我是 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
]}

这是 Ajax 调用(这很可能是错误的):

var jsonFile = $.ajax({
  method: "GET",
  url: "filepath/filename.json",
  dataType: "JSON"
});

然后我需要在几个函数中使用该信息:

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);
}

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

【问题讨论】:

  • 你应该在提问之前检查jQuery API,因为它有很多选择而不是你将拥有的答案

标签: javascript json ajax web


【解决方案1】:

您必须取得成功才能处理收到的回复。示例

$.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 调用现已修复。我缺少的主要部分是 jsonFile.done(function(dataHere){}) 部分。现在我遇到了另一个由谷歌地图 API 引起的问题,我将在其他地方发布。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    最好使用回调,因为这样不会阻塞。 JQuery 还有一个 getJSON 函数,它将 Ajax 调用返回的字符串解码为 JSON,并以 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);
            });
    }
    

    https://api.jquery.com/jQuery.getJSON/

    【讨论】:

      【解决方案4】:
      $.ajax({
          url: 'Your service url',
          type: 'GET',
          dataType: 'json',
          url: "filepath/filename.json",
          success: function(data){
              console.log(data);
           }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-17
        • 1970-01-01
        • 2013-10-02
        • 2016-06-06
        • 1970-01-01
        • 2013-01-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多