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

3
  • 1
    Create a <script> tag, append ur code into it, append the whole script element to the body of the current document Commented Mar 29, 2016 at 9:58
  • stackoverflow.com/questions/9129666/… Commented Mar 29, 2016 at 9: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. Commented Mar 29, 2016 at 10:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.