Is there any way to wait for AJAX response and halt execution?

前端 未结 6 982
囚心锁ツ
囚心锁ツ 2020-12-24 10:42

Here is some code I\'d like to execute. I\'d like to wait for AJAX response so I can return something from the server. Any way to achieve this?

function func         


        
6条回答
  •  星月不相逢
    2020-12-24 11:20

    New, using jquery's promise implementation:

    function functABC(){
    
      // returns a promise that can be used later. 
    
      return $.ajax({
        url: 'myPage.php',
        data: {id: id}
      });
    }
    
    
    functABC().then( response => 
      console.log(response);
    );
    

    Nice read e.g. here.

    This is not "synchronous" really, but I think it achieves what the OP intends.

    Old, (jquery's async option has since been deprecated):

    All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

    async: false 
    

    like described here

    Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

提交回复
热议问题