How to access remote JSON data as local array
I can use JQuery's $ .get function to access JSON data from a different url, but how can I use that data (as an array) elsewhere in my code?
Consider the following code:
<script type="text/javascript">
$(function () {
$.get("/some/other/url/that/returns/json", function(data){
var d = eval(data);
});
alert(d);
</script>
It doesn't work, but it shows what I would like to do. Thanks in advance for your help / advice.
source to share
Doing this action:
<script type="text/javascript">
var d;
$.get("/some/other/url/that/returns/json", function(json){
d = json;
}, "json");
</script>
you get the answer json
, and if it's already an array, you don't need to do anything. Also, use eval()
as little as possible . (Not great at all)
Be careful if it d
doesn't matter until after the answer appears, so your code should handle that. Most likely you will call a function that uses d
from $ .get ("...", function (json) {} , "json").
<script type="text/javascript">
var d;
useArray = function(d){
//Operations that involve the response
}
$.get("/some/other/url/that/returns/json", function(json){
d = json;
// Operate over "d" once your server
useArray(d);
}, "json");
</script>
Of course, since you now have all the operations on d
a separate function, you can simply do this
<script type="text/javascript">
useArray = function(d){
//Operations that involve the response
}
$.get("/some/other/url/that/returns/json", function(json){
useArray(json);
}, "json");
</script>
If you need to rejoin d
, you need to change your code as needed. This is just a guide.
source to share