3

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');
    }
});
14
  • 1
    eval but this is bad practice Commented Jun 10, 2013 at 6:34
  • Cherniv, I don't think so. It doen't work - 'not a function'. Can u provide a demo? Arun P Johny, I've unparse function... stackoverflow.com/questions/17014735/… Commented Jun 10, 2013 at 6:43
  • look: jsfiddle.net/7W4CU Commented Jun 10, 2013 at 6:48
  • @Cherniv, okey... No surprise - you've executed the string. That was not the question. Tnx anyway! Do you know how to get jquery object from this string? Commented Jun 10, 2013 at 7:06
  • 1
    so you need this: var myAjaxParamObj = { url: 'index.php', type: 'post', data: 'somevar=' + somevar, dataType: 'json', success: function(json) { alert('test'); } } ; Commented Jun 10, 2013 at 7:25

1 Answer 1

2

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)();
Sign up to request clarification or add additional context in comments.

2 Comments

Thx, sorry, it is simple code for demo. Fixed. Anyway, in this case I'll get function, but not jQuery object.
thx a lot, but i don't need to execute this function. Updated question to be more specific.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.