1

我有一个通过将方法名称和数据作为参数进行 Asp.Net Web 服务调用的函数。将数据发送到服务没有问题。但我的回报值是undefined

function ServiceCommand(method, mdata) {
            $.ajax({
                url: "Service1.asmx/" + method,
                type: "POST",
                dataType: "json",
                data: mdata,
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    return msg;
                },
                error: function (e) {
                    return "error";
                }
            });
        }

function Insert()
{
var Msg = ServiceCommand("HelloWorld", "{pwd:'1234',txt:'SomeText'}");
alert(Msg);// undefined

}

如何让 ServiceCommand 函数等到响应到来?我正在使用 JQuery 1.9(async:false不起作用)我看到了一些建议使用的解决方案,$.When但我无法弄清楚如何在这里使用。

4

2 回答 2

2

不使用承诺 (.when) 的一种简单方法是将回调函数作为第三个参数传递给 ServiceCommand。这个函数会做任何你需要对来自 ajax 调用的响应做的事情。

function ServiceCommand(method, mdata, onSuccessCallback) {
        $.ajax({
            url: "Service1.asmx/" + method,
            type: "POST",
            dataType: "json",
            data: mdata,
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                if (onSuccessCallback !== undefined) {
                    onSuccessCallback(msg);
                }
            },
            error: function (e) {
                return "error";
            }
        });
    }

function Insert()
{
    var Msg = ServiceCommand("HelloWorld", "{pwd:'1234',txt:'SomeText'}", onSuccess);
    alert(Msg);
}
function onSuccess(msg)
{
    alert(msg);
}
于 2013-04-22T19:06:54.310 回答
1

使用异步=假;

$.ajax({
   url: myUrl,
   dataType: 'json',
   async: false
于 2013-04-22T18:59:46.440 回答