user3180943 user3180943 - 1 year ago 63
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)

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?

@foreach (var item in splitted)
'@Html.Raw(Model.GetHost(ViewBag.Foo, ViewBag.Bar))' + '@item', {
context: { item: '@item' }

@if (i != count)

.then(function() {

Answer Source

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) {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download