2016-01-22 41 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>

相關問題