Passing JSON with functions via AJAX

Will

New Member
#1
Quite simply, I'd like to "re-hydrate" functions which are passed from AJAX, as follows:
Mã:
//AJAX response:
{"foo":"bar","baz":"function(){console.log('I am back working as a function!');}"}
And obviously, baz should be a function and not a string. How would I do this?
 

Admin

Administrator
Thành viên BQT
#2
It's possible, but of course we must use the evil eval .. use at your own risk!!
Mã:
var ajaxResponse = {"foo":"bar","baz":"function(){console.log('I am back working as a function!')}", "lambda": "() => console.log('Hello i\\'m a lambda')"};

function isAFunction(v) {
    try {
        eval("var f = " + v);
        return typeof f === "function";
    } catch (e) {
        return false;
    }
}

var result = Object.entries(ajaxResponse).reduce((obj, [key,value]) => {
      if (isAFunction(value)) {
          eval("obj[key] = " + value);
      } else {
            obj[key] = value;
      }
      return obj;
      
}, {});

result.baz();
result.lambda();
 
Top