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

前端 未结 6 2433
南旧
南旧 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:17

    jQuery AJAX requests are made asynchronously, meaning that the request is started and the $.post() method returns more or less immediately. The request is processed by the browser in the background. When the request is completed, jQuery calls the callback function you supplied to $.post(). You can use async: false to tell jQuery to block until the request completes, but this is not recommended as it will almost certainly result in terrible performance and a poor user experience.

    What you should do instead is write your code such that the logic that depends on the AJAX response is kicked off by your callback function. Something like:

    function handleAjaxResponse(responseData) {
      // do something with the response.
    }
    
    function doAjax() {
    
      $.post("demo_test_post.asp",
        {
          name:"Donald Duck",
          city:"Duckburg"
        },
        function(data, status){
          handleAjaxResponse(data);
        });
    
    }
    
    doAjax();
    

提交回复
热议问题