user3180943 user3180943 - 1 month ago 5
jQuery Question

Convert ajax call string to actual deferred object, is it possible?

is it possible to convert a string like "$.ajax(...)" to an actual object?

I generate a List with C# with ajax calls to apply to jQuery $.when().

arrCalls = ["$.ajax({ url: 'url....' })",
"$.ajax({ url: 'url....' })"];

$.when.apply($, arrCalls)
.then(...


But this is not working. I think because the values are not actual deferreds but strings.

Do I need to keep this ugly code or can I somehow refactor it?

$.when(
@foreach (var item in splitted)
{
<text>
$.ajax(
'@Html.Raw(Model.GetHost(ViewBag.Foo, ViewBag.Bar))' + '@item', {
context: { item: '@item' }
})

@if (i != count)
{
<text>,</text>
}
</text>

i++;
})
.then(function() {
...

Answer

You can store the calls to the ajax method (that will be deferred) in an array and call those

This should work.

function GetAjaxCall(url) {
    return $.ajax({
        url: url  // Set other properties as needed.
    });
}
$(function () {

    var arrUrls = ['@Url.Action("Add")', '@Url.Action("StudentLookup")'];
    var calls = [];
    $.each(arrUrls,function(a, b) {
            calls.push(GetAjaxCall(b));
    });


    $.when.apply($, calls)
        .then(function() {
            console.log('all done');
    });

});
Comments