简体   繁体   中英

Assign value to global variable using $.Ajax (JQuery)

I am creating new functionality where I build a grid based on Json data returned from Ajax. I have decided I want to encapsulate this functionality within a function, so when I add/update/delete, I can on success retrieve a new representation of the data.

The problem I am having is I want to fill a global array but once my function that uses AJAX ends, I have an Array but no data. This isn't a problem when all the code is within the AJAX call but once I try to separate this in to its own function, it doesn't work as intended.

 <script type="text/javascript">
    var DataArray = [];

    // Use this function to fill array
    function retrieveNotes() {
        $.ajax({
            url: "http://wks52025:82/WcfDataService.svc/GetNotesFromView()?$format=json",
            type: "get",
            datatype: "json",
            asynch:true,
            success: function (data) {
                returnedData = data;
                $.each(data.d, function (i, item) {
                    DataArray[i] = [];
                    DataArray[i][0] = item.NotesTitle.trim();
                    DataArray[i][1] = item.ProfileName.trim();
                    DataArray[i][2] = item.IsShared;
                    DataArray[i][3] = item.NameOfUser.trim();
                }) // End of each loop
            }
        });
    }


    $(document).ready(function () {
        retrieveNotes();
        DataArray;
    </script>

It's asynchronous, so you'll have to wait for the ajax call to finish before you can use the data :

function retrieveNotes() {
    return $.ajax({
        url: "http://wks52025:82/WcfDataService.svc/GetNotesFromView()?$format=json",
        type: "get",
        datatype: "json"
    });
}

$(document).ready(function () {
    retrieveNotes().done(function(data) {
        var DataArray = [];
        $.each(data.d, function (i, item) {
            DataArray[i] = [];
            DataArray[i][0] = item.NotesTitle.trim();
            DataArray[i][1] = item.ProfileName.trim();
            DataArray[i][2] = item.IsShared;
            DataArray[i][3] = item.NameOfUser.trim();
        });
        // you can only use the data inside the done() handler,
        // when the call has completed and the data is returned
    });
});

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