How to get return value in a function with inside Ajax call - JQuery

后端 未结 5 1206
遥遥无期
遥遥无期 2021-01-07 02:39

this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(

function         


        
5条回答
  •  借酒劲吻你
    2021-01-07 03:32

    That's because the $.ajax() call is asynchronous.

    If you edit your code to something like:

    function getMessageCount(callback) {
        var count;
        $.ajax({
           type: "POST",
           url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           success: function (data) {                            
             count = data.d;
    
             if(typeof callback === "function") callback(count);
          } //success
       });
    }
    

    Then when you call it:

    getMessageCount(function(count){
      console.log(count);
    });
    

提交回复
热议问题