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

前端 未结 6 2477
南旧
南旧 2020-12-19 05:39

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 th

6条回答
  •  余生分开走
    2020-12-19 06:05

    A jQuery post() is by default Asynchronous meaning that you can never return a value from a function like this.

    To Quote the jQuery Docs

    async (default: true)

    Type: Boolean

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

    You would need to provide a callback function in order to update the value.

    e.g. A very basic example.

    var foo;
    test();    
    
    function test(){    
        $.post("demo_test_post.asp",
            {
              name:"Donald Duck",
              city:"Duckburg"
            },
            function(data,status){
    
              var bar = "bar"
              foo = bar; // assign foo
    
            });    
        }    
    }
    

    Alternatively you can look at changing your jQuery Ajax to be Synchronous. Take a look at this post here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

提交回复
热议问题