简体   繁体   中英

ASP.NET: jQuery Ajax result not defined

I have this jQuery ajax:

        // ... omitted code ...

        var data = "{'TagName':'" + TagName + "'}";

        var resultSet = 0;

        jQuery.ajax(
        {
            type: "POST",
            url: '<%= ResolveUrl("~/Webservices/TagWebServices.asmx/GetTagByTagName") %>',
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (t)
            {
                resultSet = t.d;
            }
        });

        jQuery(this).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
        resultSet.desc +
        "</div>" );

        // ... omitted code ...

The problem is that resultSet.desc always returns "undefined" BUT when I use Firebug and add a breaking point in the last line and then click (Continue) resultSet.desc works as expected.

An ajax call is Asynchronous (by definition...). So you have to put the affectation in the success handler:

$.ajax({ ...
    success : function(t) {
        resultSet = t.d;
        jQuery(this).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
            resultSet.desc +
        "</div>" );
    }
)};

Ajax is asynchronous by default. You could try to set ajax request synchronous setting: async:false, but this is a bad way.

The way to go is to code your logic in the success callback function keeping ref on 'this' object.

var data = "{'TagName':'" + TagName + "'}";

        var resultSet = 0,
            that = this;

        jQuery.ajax(
        {
            type: "POST",
            url: '<%= ResolveUrl("~/Webservices/TagWebServices.asmx/GetTagByTagName") %>',
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (t)
            {
                resultSet = t.d;
                 jQuery(that).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
                    resultSet.desc +
                    "</div>" );
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM