Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to jQuery ajax function object

Is there any way to convert this string to jQuery function/object?

var str = '';
str=str+"$.ajax({ ";
str=str+"url: 'index.php', ";
str=str+"type: 'post', ";
str=str+"data: 'somevar=' + somevar, ";
str=str+"dataType: 'json', ";
str=str+"success: function(json) { ";
str=str+"alert('test'); ";
str=str+"} ";
str=str+"}); ";

I want to get the same result as...

var myFunction = $.ajax({
    url: 'index.php',
    type: 'post',
    data: 'somevar=' + somevar,
    dataType: 'json',
    success: function(json) { 
        alert('test');
    }
});
like image 692
Yevgen Avatar asked Jun 30 '26 13:06

Yevgen


1 Answers

you can use Function constructor.

var your_function = new Function(str);

but you have 2 errors in your string, you can't put // because you will comment everything after that (you don't have new lines) and you have 1 reduntant closing curly brace.

EDIT: to get jquery object, you can execute that function

var somevar = 'something';
var str = '';
str=str+"return $.ajax({ ";
str=str+"url: 'index.php', ";
str=str+"type: 'post', ";
str=str+"data: 'somevar=' + somevar, ";
str=str+"dataType: 'json', ";
str=str+"success: function(json) { ";
str=str+"} ";
str=str+"}); ";

var ajax = new Function(str)();
like image 92
jcubic Avatar answered Jul 02 '26 04:07

jcubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!