How to Execute Scripts Injected via innerHTML after AJAX
Inserting HTML content dynamically through AJAX is a common practice. However, sometimes this content includes script tags that need to be executed. However, these scripts may not execute automatically when injected via innerHTML.
Problem:
Consider a div named "Content" that should be filled with data from a PHP file through AJAX, including a script tag. However, the script within the tag is not being executed:
<div>
Solution:
To execute scripts injected via innerHTML, you can use the following code:
var arr = MyDiv.getElementsByTagName('script'); for (var n = 0; n < arr.length; n++) eval(arr[n].innerHTML);//run script inside div
This code iterates through all script tags within the div and evaluates their innerHTML as JavaScript.
The above is the detailed content of Why Don\'t My AJAX-Injected Scripts Execute, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!