如何获得返回值与内部Ajax调用的函数 - JQuery的如何获得、函数、返回值、Ajax

2023-09-10 17:02:58 作者:像风一样自由

这听起来可能很容易就你们几个,但我无法弄清楚,为什么我不能够得到的返回值,甚至chceking很多帖子后:(

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 getMessageCount() {
                    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;
                        } //success
                    });
                    return count;
                }

现在如果我叫 VAR数= getMessageCount(); 它给了我undefinted :( 而里面的方法计数到来正确的,即服务工作正常。

Now if I call var count = getMessageCount(); it gives me undefinted :( while inside the method count is coming correct, i.e. service is working fine.

推荐答案

这是因为 $。阿贾克斯()调用是异步的。

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

如果您修改了code到是这样的:

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);
});
 
精彩推荐
图片推荐