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

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

why cant I return data from $.post (jquery)

I must be making a silly mistake but I cannot return the data I get from a $.post function and store it in a variable, not only that, I cannot return ANYTHING from within that function. Example:

function test(){

$.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      return(data)
    });

}

var foo = test()
alert(foo)

it say's that foo is undefined. But to take it a step further, even when I do this:

function test(){

    $.post("demo_test_post.asp",
        {
          name:"Donald Duck",
          city:"Duckburg"
        },
        function(data,status){

          var bar = "bar"
          return(bar)
        });

    }

    var foo = test()
    alert(foo)

it STILL says foo is undefined... I must be doing something wrong or misunderstanding something. Can someone please help.

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

$.post is a asynchronous function. The control from function will immediately return after it run post but the response from post may be received later.

So what you can do is instead of return, use a call back function and define callback function outside.

say,

function test(){

  $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      my_function(data)
    });

}

function my_function(data){
  // you can operate on data here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...