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');
}
});
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)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With