Reputation: 15835
The following code exists in one of the JavaScript files I am working on, which contains jQuery Ajax code.
I saw the response result below and it's a JSON string which is manually created by the backend.
I'm not sure what the point of running eval() on a response like that is. What exactly is eval()
doing here?
success: function (response) {
var response= response.replace(/\\/g, "%5C");
eval(response);
},
Upvotes: -1
Views: 8359
Reputation: 499152
eval
executes the passed in string as if it were javascript code.
What exactly happens depends entirely on the contents of response
.
That is, the value of the response
variable that is passed to the eval
function gets evaluated as normal javascript.
If response
was "alert('Hello from evel!');"
, you would see an alert box with the text "Hello from evel!".
Upvotes: 7
Reputation: 490443
eval()
executes a string as JavaScript code in the context of its execution context. Generally, this means scoped to whatever function it is in.
It is often used to evaluate a JSON string. Note that if you are eval()
ing a JSON string, you should wrap it in parenthesis ((
& )
). The parenthesis means it will always be evaluated as an expression, not a block.
Upvotes: 3