Search code examples
javascriptjqueryeval

What does the eval() method do in an Ajax response?


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); 
},

Solution

  • 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!".