在jQuery上使用数组和多个对象的JSON响应,数据无法成功

时间:2017-05-22 18:03:44

标签: jquery json rest

我目前正尝试使用以下链接中的jQuery以JSON格式获取数据:http://localhost:8181/rest/stuff。此链接显示了一个包含多个对象的数组。当我尝试以下代码时:

function loadStuff() {
    $(document).ready(function() {
        $.ajax({
            url: 'http://localhost:8181/rest/stuff',
            dataType: 'json',
            success: function(data) {
                alert('Success!');      
            },
             error: function() {
                 alert('error getting JSON about stuff');
            }
        });
    }); 
}

它没有显示“成功!”,而是它给了我错误提示。而链接工作正常。我尝试使用其他几个JSON API,它运行良好。

编辑(来自链接的JSON响应示例):

[
  {
    "id": "CHN",
    "country": "China",
    "continent": "Asia",
    "region": "Eastern Asia",
    "surface": 9572900,
    "population": 1277558000
  },
  {
     // Same object
     ...
     ...
     ...
  }
]

1 个答案:

答案 0 :(得分:0)

首先尝试通过重写ajax调用来捕获错误(请参阅错误回调函数)。

$.ajax({
        url: 'http://localhost:8181/rest/stuff',
        dataType: 'json',
        success: function(data) {
             console.log(data);
             alert('Success!');      
        },
        error: function(jqXHR, exception) {
             console.log(jqXHR);
             console.log(exception);
        }
    });