这听起来对你们中的几个人来说很容易,但是我什至无法弄清楚为什么我即使在收到很多帖子后也无法获得返回值:(
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 count = getMessageCount(); 它给了我不确定的:(当方法内部计数正确时,即服务运行正常。
var count = getMessageCount()
那是因为$.ajax()调用是异步的。
$.ajax()
如果您将代码编辑为以下内容:
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 }); }
然后,当您调用它时:
getMessageCount(function(count){ console.log(count); });