1

I know its a bit confusing question. Please let me elaborate.

I need to execute a jquery script written in a text file that I am getting from a ajax request.

e.g. I am getting the following code from ajax request

($($("#jstreeblock").children().children().children()[0]).children('li').attr('id'))

I need to execute and store the result of above script in a variable.

for another and simple example. I have gotten

'a'+'b'

if i execute the above script the result will be ab but if I am running it with eval I am getting error

script

<script>
var a = "'a'+'b'"
console.log(a); // printing 'a'+'b'
eval(a); // it should give ab but not giving any result
</script>

if I am running it as

eval(''a'+'b'') 

is giving error, given below

error

VM157982:1 Uncaught SyntaxError: Unexpected string(…)(anonymous function) @ VM157981:2InjectedScript._evaluateOn @ VM156978:878InjectedScript._evaluateAndWrap @ VM156978:811InjectedScript.evaluate @ VM156978:667

Please help and many thanks

Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100
  • 1
    Create a ` – Ahs N Mar 29 '16 at 09:58
  • http://stackoverflow.com/questions/9129666/whats-the-better-practice-eval-or-append-script – SilentTremor Mar 29 '16 at 09:59
  • 3
    While possible, it's definitely a better idea to avoid executing scripts you receive, an hijacker might be able to execute malicious code. If possible, try just sending data and do something based on the data you receive. – Vale Mar 29 '16 at 10:02

1 Answers1

1

Normally eval should work in this case. But really not sure how you are calling it. You say that you are calling it as eval(''a'+'b''), which should be eval("'a'+'b'"). That might also be the reason.

Now, regarding eval, it is a dangerous idea to use it as @Sosdoc suggests. However, Just to address your case, check this fiddle where I have a mocked json response and the eval works fine. I have also added [commented] your "'a'+'b'" case. You can check that as well. It should give you ab as a result.

Also find this excellent answer from user @Chocula here to know more about this,

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

Community
  • 1
  • 1
Thomas Sebastian
  • 1,582
  • 5
  • 18
  • 38