2016-01-22 97 views
0

我试图在简单的Ajax调用上工作,但我无法弄清楚出了什么问题。 ajax调用成功,但没有任何警报。当我console.log(myStats),它显示在我的控制台JSON虽然。成功的Ajax调用不返回数据

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

输出什么,你得到 –

+1

'JSON.parse(JSON.stringify(数据))'你会得到警告做。 –

+0

console.log(data)的输出是什么,是对象还是字符串? –

回答

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

而是成功调用的后面,使用Deferred对象。

成功使用.done()。

这个工程。

+0

使用'done()'没有什么错,但是'success'回调有什么问题? – billynoah

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>