Reputation: 430
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 : "[email protected]",
}
$('#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>
Upvotes: 0
Views: 1282
Reputation: 924
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
Upvotes: 0
Reputation: 36732
$.getJSON
runs asynchronously. In your current code you are trying to access data before the request has completed.
You need to use the success callback to access the response.
$.getJSON(url, function(data) {
console.log(data);
console.log(outp);
console.log("Hi");
});
Upvotes: 0