2012年9月13日 星期四

JQuery Ajax call return an Array

If you are looking for how to use JQuery ajax call return an Array Object.
A simple code as below: (it spend me a lot of time.. & most of artical sample does not work in my case. )

[notice] the async parameter of ajax function might need set as false. at least in my case need.
otherwise you might encounter your return value always be empty.

function myAjaxCallReturnValue( )
{
var mAJAXVariable = (function ()
    {
        var mDPList = new Array();
        $.ajax({
            type: "GET",
            url: _FileURL,
            async: false,
            dataType: "xml",
            beforeSend: function ()
            {
                $('#lblResult').hide();
            },
            complete: function ()
            {
                $('#lblResult').show();
            },
            success: function (xmlResult)
            {
                var mResult = "";
                $(xmlResult).find("Item").each(function ()
                {
                    var mDPinfo = new clsDataPointObject();
                    var mUCPTname = $(this).find('UCPTname').text();
                          mDPinfo.setUCPTname(mUCPTname);
                          mDPList.push(mDPinfo); // Add custom object into array
                });
            }
        });
        return mDPList; // return array to function caller
    })();
    return mAJAXVariable; // return variable (in my case the variable is an Array Object)
}

how to use it?

var mReturnValue = myAjaxCallReturnValue( );
and you can check by simply Alert( ) command.

e.g
$( "#Result").text(mReturnValue.length is " + mReturnValue.length);

what else?

try to change  async: true.
you will see your return value always be empty. (expect use alert command).