开发者

Trying to get a json result back from method in another namespace, having issues

I have a seperate .js file and namespace for json requests. I have another .js file and namespace for the actual logic.

I can't seem to get the result back in my logic layer.

var jsonResult = Blah.Data.LoadAggregates();

alert(jsonResult);
alert(jsonResult.d.length);
alert(jsonResult.length);

all of the above calls are returning undefined.

Blah.RegisterNamespace("Blah.Data");

(function(Data) {


    Data.LoadAggregates开发者_Python百科 = function() {

        $.ajax({
            type: "POST",
            url: "asdf.asmx/GetAggregates",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                ???????

            },
            error: function(msg) {
                alert("error" + msg);
            }
        });

    };

})(Blah.Data);  


AJAX calls are asynchronous, meaning that the $.ajax call will not wait for the server to respond.

Therefore, your LoadAggregates function finishes executing before the server replies.

In order to get the server's response, your LoadAggregates function needs to take a callback parameter, the way $.ajax does.

For example:

Data.LoadAggregates = function(callback) {

    $.ajax({
        type: "POST",
        url: "asdf.asmx/GetAggregates",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            //Do something to the data if you want to

            callback(data);        //You can pass any parameters you want
        },
        error: function(msg) {
            alert("error" + msg);
        }
    });

};

You would then call it like this:

Blah.Data.LoadAggregates(function(jsonResult) {
    alert(jsonResult.length);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜