Home > Web Front-end > JS Tutorial > Why Don\'t My AJAX-Injected Scripts Execute, and How Can I Fix It?

Why Don\'t My AJAX-Injected Scripts Execute, and How Can I Fix It?

Susan Sarandon
Release: 2024-11-19 17:09:03
Original
979 people have browsed it

Why Don't My AJAX-Injected Scripts Execute, and How Can I Fix It?

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template