2017-09-14 4 views
0

Ich möchte Stadt von der gegebenen API bekommen und es anzeigen. Die Ausgabe auf der Konsole ist undefined. Das ist, was ich bis jetzt habe:Wie extrahiere ich Informationen aus einem JSON-Objekt in Javascript?

$.getJSON("http://ip-api.com/json", function(data1){ 

    city = data1.city; 
    $("#city").html(city); 

    }); 
    console.log(city); 

Wie kann ich das erfolgreich machen?

+2

In Ihrem Fall haben Sie einen asynchronen Aufruf, so dass, wenn console.log Stadt ist nicht definiert genannt wird. Sie sollten console.log innerhalb des Erfolgs-Callbacks verschieben – Alcruz

Antwort

0

$.getJSON("http://ip-api.com/json", function(data1) { 
 
    city = data1.city; 
 
    $("#city").html(city); 
 
    console.log(city); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="city"></div>

Verwandte Themen