jqueryjsongetjsonreadystate

Json file wont load in with jquery .getJSON()


I'm trying to assign a external json file to a var with jquery's getJSON(). In my JSON file i have the same exact code as for outp. when I try to console.log what is in the data var, it only show's readyState1. That means that I'm connected with the server, but why doesnt the request keep going? Here is my code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    var url = "content.json"
    var outp = {
                    low         :   0,
                    high        :   99,
                    name        :   "Fritz",
                    rufnummer   :   "012",
                    faxnummer   :   "345",
                    mobil       :   "678",
                    mail        :   "mail@mail.mail",  
                }

    $('#find').on("click", function(){

        var data = $.getJSON(url);

        console.log(data);
        console.log(outp);
        console.log("Hi");

    });
});
</script>
</head>
<body>
    <p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" id="inp">
    <button type="button" id="find">Finden</button>
    <p class="output"></p>
</body>
</html>

Solution

  • the method $.getJSON performs an asynchronous call, meaning you will not get the received data as return value. In order to access the response, sent by the server, you need to register a callback:

    $.getJSON(url, function(data) {
          console.log(data);
          //do what you need to do with your data here
    });
    

    References http://api.jquery.com/jquery.getjson/

    Hope this helps