2

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.

3
  • 2
    FYI, you can add a 'type' arg to your call and avoid the eval: $.get('url', function(data){...},'json') Commented Aug 21, 2009 at 17:40
  • jquery does eval internally..with the json dataType set Commented Aug 24, 2009 at 12:56
  • Only on the browsers that lack JSON parsers (i.e.: IE) Commented Aug 24, 2009 at 20:53

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for keeping me away from eval(), voyager. I've got a question about handling the "undefined" problem, though -- please see presleyster's answer & chime in if you can help. Thanks again, JP.
0

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

Comments

0

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){...});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.