【问题标题】:ASP.NET Javascript to web service get return value outside of callback functionASP.NET Javascript 到 Web 服务在回调函数之外获取返回值
【发布时间】:2015-07-28 01:56:33
【问题描述】:

我有一个 ASP.NET Web 服务,它返回一个简单的字符串值,我正在使用脚本管理器通过 javascript 调用这个 Web 服务,一切正常,但是,我需要来自我所在位置的返回值调用 Web 服务,并从回调函数中“不”。

类似这样的东西(抱歉伪代码不好)

function something() {
scriptmanager.webservice.method1(param, OnSuccess);
}
function OnSuccess(retVal) {
retVal <-- I need to do more with this, from within the "something" function above. Building an array for example calling this service multiple times.
}

我尝试在函数之外创建一个全局 javascript 变量,并在 OnSuccess 函数中分配它,但它总是从“某事”函数中出现未定义。

那里的所有示例通常会在页面上进行视觉上的更改,并且不会真正对 Web 服务返回值做一些有用的事情,我如何将返回值恢复到主调用“某事”函数?

【问题讨论】:

  • 您需要阻止该线程,直到收到响应。所以就像一个while循环检查来自AJAX调用/承诺的返回变量。

标签: javascript asp.net web-services scriptmanager pagemethods


【解决方案1】:

您描述的是同步请求而不是异步请求,ASP.NET ScriptManager 只支持异步调用。

但是,您可以使用 jQuery .ajax() 函数进行同步调用,如下所示:

function something() {
    var resultOfMethod1;

    $.ajax({
        type: "POST",
        async: false,
        url: "PageName.aspx/Method1",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            resultOfMethod1 = result.d;
        }
    });

    // Do something here with resultOfMethod1
    // resultOfMethod1 will have the result of the synchronous call
    // because the previous $.ajax call waited for result before executing 
    // this line

}

【讨论】:

  • 谢谢朋友。你救了我很多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多