Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following script:

var myData;

$.ajax({
    url: "/foo.php",
    dataType : 'json',
    type: "POST",
    async: false
  })
  .done(function( data ) {
       myData = data;
  });

All I want to do is assign the data from the ajax response to myData and refer to this variable further down in my script. The above code seems to work but relies on async: false which I've read is not a good thing. If I comment this out (and therefore it uses the default async: true) nothing is assigned to myData.

I've read the following post jQuery ajax success callback function definition but can't adapt that so I can access the data in myData. I also note that question was asked in 2013 so not sure if it's still accurate or the right way to go about this?

How is this supposed to be done? I'm using jquery v1.11.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

Ok so the following seems to work. I've removed async: false and added a function where I'm referring to the data from the ajax call.

$.ajax({
    url: "/foo.php",
    dataType : 'json',
    type: "POST"
})
.done(function( data ) {
   buildTree(data);
});

function buildTree(data) {
   console.log(data);
   // other code that needs 'data'
}

I assume this is correct based on what @pwolaq suggested.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...