views:

372

answers:

3

I'm able to use Jquery's $.get function to access JSON data from another 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>

That's not functional, but it show's what I'd like to do. Thanks in advance for your help/tips.

A: 

make d a global variable. Or assign it to whatever needs to use it.

Zoidberg
+1  A: 

Doing this:

<script type="text/javascript">
var d;

$.get("/some/other/url/that/returns/json", function(json){
    d = json;
}, "json");
</script>

you'll get the json response, and if its already an array, you wont be needing to do anything else. Also, please use eval() as little as possible. (Not at all is great)

Be carefull that d wont have any value until there is a response, so your code should deal with that. Most likely, you'll call the function that uses d from within $.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, as you now have all operations over d on a separate function, you could 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 acces again to d, you should modify your code as needed. This is only a guide.

voyager
trisignia
A: 

FYI, you can add a 'type' arg to your call and avoid the eval: $.get('url', function(data){...},'json')

Or you can use $.getJSON('url', function(data){...});

devpl