I have a webpage that makes an AJAX request to a PHP script. That PHP script responds with a valid JSON object, and sets the Content-type
header to application/json
.
The JSON format is as follows (as reported by console.log(JSON.stringify(data))
where data
is the JSON response):
{
"content": "<script type=\"text/javascript\">console.log(\"test\");</script>"
}
I then create a div with the class of "content" (remember data
is my AJAX responseText JSON object):
var content = document.createElement("div");
content.setAttribute("class", "content");
content.innerHTML = data.content;
Finally, I append the content div to an existing div on my site.
existingDiv.appendChild(content);
I examine the source in the elements
tab of Google Chrome's developer tools because it does a good job of showing what is an actual DOM node, and what is just text. The script block shows up as a DOM node.
Unfortunately, the script is not executed - console.log("test");
does not output test
to the developer tools console.
The only option I've seen so far is to use eval()
which I'm trying to avoid like the plague. Also, my content might contain more than just a script block. It could contain other HTML markup as well.
What am I missing? How can I get this dynamically added block of Javascript to execute?
A jQuery solution is acceptable.