简体   繁体   中英

Javascript not loading on Ajax div load

I have a standard html page index.php and within this page I have a

<div id="alertMe">...</div>

I use a simple onclick function to do an AJAX change of this div. I wont paste the whole Ajax call.

xmlhttp.open("GET","message.php?msg=hello" , true); 

message.php loads and I can display the $_GET['msg'] value in the alertMe div. However, I have a simple javascript alert which is in the file message.php

<script type="text/javascript">
  alert("I am an alert box!");
</script>

I cannot get the alert to popup. Is this because I am trying to run javascript within a div load? I would have thought that was a common requirement.

Any ideas?

==== Including files =====

index.php

<html>
 <script>
    function loadMsg(moduleID) {
        var xmlhttp;
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {  // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("alertMe").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","message.php?msg=hello" , true);
        xmlhttp.send();
    }
</script>
<body>
    <div id="alertMe"></div>
    <a href="javascript:void(0);" onclick="loadMsg();">Load Message</a>
</body>
</html>

message.php

<?php
echo $_GET['msg'];?>
<script type="text/javascript">
   alert("I am an alert box!");
</script>

As some of the commentators have pointed out, <script> s inside an AJAX response do not get executed when the HTML is injected into the page by setting the innerHTML property of a DOM node. If you really need to execute those scripts:

function setHtml(element, html) {
    element.innerHTML = html;

    var scripts = element.getElementsByTagName("script"),
        i = 0, script;

    for (i; i < scripts.length; i++) {
        script = scripts[i];

        if (script.type = "text/javascript" && !script.src) {
            eval(script.innerHTML);
        }
    }
}

Edit: I personally recommend against this. The "success" handler for your AJAX call should contain the logic you need to run post-AJAX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM