Ok, thats how it work. Thanks for your answer. :)

Cheers / David

On Oct 20, 6:38 pm, MorningZ <morni...@gmail.com> wrote:
> "Why, and how can I make it work??? "
>
> Because you aren't understanding asynchronous behavior...
>
> The script doesn't "wait" for the $.getJSON call to finish before
> continuing on.... you'll need to do your work with "content" inside
> the success event, even if that means calling another function passing
> the json to it, like:
>
> var content = 'empty';
>             $.getJSON("getjson.json",
>                 function(json){
>                     content = json.layout.template[1].content;
>                     SomeFunction(content);
>                 });
>
> On Oct 20, 12:30 pm, Dave <messedupp...@gmail.com> wrote:
>
>
>
> > Hi
>
> > In the code below the second alert is executed before the first one
> > making it show the "empty" content, and not the result from the .json
> > file. Why, and how can I make it work???
>
> > -------------------------------------------------
> > getjson.html file
> > -------------------------------------------------
> > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
> > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
> > <html xmlns="http://www.w3.org/1999/xhtml";>
> > <head>
> >     <title>getJson</title>
> >     <script type="text/javascript" src="http://code.jquery.com/jquery-
> > latest.js"></script>
> >     <script type="text/javascript">
> >         $(document).ready(function(){
> >             var content = 'empty';
> >             $.getJSON("getjson.json",
> >                 function(json){
> >                     content = json.layout.template[1].content;
> >                     alert(content);//This work
> >                 });
> >             alert(content); //This don't
> >         });
> >     </script>
> > </head>
> > <body></body>
> > </html>
>
> > -------------------------------------------------
> > getjson.json file
> > -------------------------------------------------
> > {
> >         "layout":
> >         {
> >                 "template":
> >                 [
> >                         {
> >                                 "key": "01",
> >                                 "content": "<span 
> > id=\"span1\">010101</span>"
> >                         },
> >                         {
> >                                 "key": "02",
> >                                 "content": "<span 
> > id=\"span2\">020202</span>"
> >                         },
> >                         {
> >                                 "key": "03",
> >                                 "content": "<span 
> > id=\"span3\">030303</span>"
> >                         }
> >                 ]
> >         }
>
> > }

Reply via email to