【问题标题】:Async AJAX calls using jQuery ASP.NET not working使用 jQuery ASP.NET 的异步 AJAX 调用不起作用
【发布时间】:2012-04-09 05:30:08
【问题描述】:

我创建了一个 web 服务,调用来自 jquery ajax 函数。但即使 async 设置为 true,它也不会异步工作..

我的 ASP.NET 网络服务代码

<System.Web.Services.WebMethod()> _
Public Shared Function sampleService(ByVal ttid As String) As String
Threading.Thread.Sleep(5 * 1000)
Return "Hello World"
End Function

JQuery 调用脚本

<script language="javascript">
$(function() {
    var tempParam = {
        ttid: 100
    };

    var param = $.toJSON(tempParam);
    $.ajax({
        type: "POST",
        url: "testservice.aspx/sampleService",
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        error: function() {
            alert("Error");
        },
        success: function(msg) {
            alert("Success")
            alert(msg.d)
        }
    });
});​    </script>

这里我将它设置为 async = true。即使这样,我也会在 5 秒后收到成功消息。这意味着不是异步的。我相信如果 async = true 它不会等待来自网络服务的消息。这其实是我的要求。

【问题讨论】:

  • 顺便说一下,你设置的选项值; async: true 是默认值。

标签: jquery ajax web-services asynchronous


【解决方案1】:

成功函数是一个回调;它被设计为在收到响应后调用。如果在服务器线程执行完成之前调用它,您如何确定成功或错误?对 Sleep 的调用会暂停当前的服务器线程,因此您的响应当然需要 5 秒钟才能恢复。

异步部分适用于直接跟随您的 ajax 帖子的 Javascript 代码。例如:

<script language="javascript">
$(function() {
    var tempParam = {
        ttid: 100
    };

    var param = $.toJSON(tempParam);
    $.ajax({
        type: "POST",
        url: "testservice.aspx/sampleService",
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        error: function() {
            alert("Error");
        },
        success: function(msg) {
            alert("Success")
            alert(msg.d)
        }
    });
    alert('This alert is asynchronous!  We do not know yet if the ajax call will be successful because the server thread is still sleeping.');
});​    </script>

【讨论】:

  • 嗨,丹...感谢您提供的清晰信息。但我对此还有一个疑问。想象一下,我的 web 服务包含一些长时间运行的代码,我们使用 ajax 进行了该 web 服务调用。我的疑问是,如果用户关闭该浏览器窗口,Web服务代码执行是否会暂停,或者即使在浏览器关闭后它会继续执行直到所有代码在Web服务中执行?
  • @user954093 我不能说权威,因为我以前从未遇到过这个问题,但我认为您的服务器端进程仍将完成执行,而与调用它的浏览器状态无关。当然,除非您在服务器端跟踪会话状态并明确希望在会话结束时中止。
  • 太棒了!如果您对我的回答感到满意,您应该接受它作为答案(点击投票按钮下方的空心复选标记)。我得到积分,你得到徽章,我们都赢了。 :)
【解决方案2】:

这里我将它设置为 async = true。即使这样,我也会在 5 秒后收到成功消息。这意味着不是异步的。我相信如果 async = true 它不会等待来自网络服务的消息。

不,async 表示工作线程被锁定并且不会执行任何其他代码(并且可能会冻结窗口...),直到它从服务器获得对其请求的响应。
这并不意味着你马上就会得到答案!

【讨论】:

    【解决方案3】:

    您是否检查过网络服务设置为在脚本中执行。

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    
    [System.Web.Script.Services.ScriptService]
    

    请检查此项并发送更新是否有效。

    【讨论】:

    • 嘿@AndrewBarber 我只是在交叉检查!有时会发生这样的情况,我们一直在工作,却忘记了一条简单的线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多