Reputation: 135
<script>
$.get("url", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
Hey, I would like to get data from url. I can get the JSON file and stringify it to json variable. But I have some struggles when I 'm trying to use json variable. Because, it is local variable. Also,
<script>
var json = "";
$.get("url", function(data, textStatus, jqXHR) {
json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
when I am trying to use json as a global variable, even I can not stringify data to it.
Question : How can I solve my problem?
Upvotes: 0
Views: 56
Reputation: 36511
It would be better to use your JSON data when it is available by putting the dependent code in a callback or a promise:
$.getJSON("url").then(function(data) {
// json is already parsed here
// put json dependent code here
});
You could also put your application logic in a function (assuming it's depending on the JSON data) and use that as your callback:
function initialize(data) {
// all of your data dependent logic here
}
$.getJSON("url").then(initialize);
Upvotes: 2