成功的Ajax调用不返回数据

时间:2016-01-22 06:11:57

标签: jquery ajax

我正在尝试处理一个简单的Ajax调用,但我无法弄清楚出了什么问题。 ajax调用成功但没有任何警报。当我在console.log(myStats)时,它会在我的控制台中显示JSON。

var main = function(){

$.ajax({
    type: 'GET',
    url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
    success: function(data) {
        var myStats = JSON.parse(data);
        alert(myStats);
    },
    error: function(){
        alert('error');
    }

});

};

$(document).ready(main);

2 个答案:

答案 0 :(得分:1)

您不需要解析响应,因为它已经是JSON。虽然ajax应该自动知道这一点,但为了确保您可以明确设置dataType。另外,你不能真正alert()一个json对象。

var main = function() {
  $.ajax({
    type: 'GET',
    url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
    dataType: 'json',
    success: function(data) {
      console.log(data);
      // do things with data here.. this for instance
      var html = jsonToHtml(data);
      $('#output tbody').html(html);
    },
    error: function() {
      alert('error');
    }
  });
};

function jsonToHtml(data) {
  var html = '';
  $.each(data, function(k, v) {
    if (typeof v === 'object') {
      html += jsonToHtml(v)
    } else {
      html += "<tr><td>" + k + "</td><td>" + v + "</td></tr>";
    }
  });
  return html;
}

$(document).ready(main);
table {
  width: 100%;
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 4px 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="output">
  <thead>
    <tr>
      <th>KEY</th>
      <th>VALUE</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

答案 1 :(得分:0)

function main(){

    $.ajax({
        type: 'GET',
        url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
    }).done(function(data){
        console.log(data)
    })
    };

    $(document).ready(main);

使用延迟对象,而不是成功回调。

成功使用 .done()。

这有效。

相关问题