ASP.NET Javascript到Web服务获取回调函数之外的返回值

时间:2015-07-28 01:56:33

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

我有一个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函数中指定它,但它总是从“something”函数中未定义。

那里的所有示例通常都会在页面上以可视方式进行更改,并且不会对Web服务返回值执行任何有用的操作,如何将返回值返回到主调用“something”函数?< / p>

1 个答案:

答案 0 :(得分:2)

您正在描述同步请求而不是异步请求,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

}