简体   繁体   English

Javascript未在Ajax div加载时加载

[英]Javascript not loading on Ajax div load

I have a standard html page index.php and within this page I have a 我有一个标准的html页面index.php,在此页面中,

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

I use a simple onclick function to do an AJAX change of this div. 我使用一个简单的onclick函数对该div进行AJAX更改。 I wont paste the whole Ajax call. 我不会粘贴整个Ajax调用。

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

message.php loads and I can display the $_GET['msg'] value in the alertMe div. message.php加载后,我可以在alertMe div中显示$ _GET ['msg']值。 However, I have a simple javascript alert which is in the file message.php 但是,我在message.php文件中有一个简单的javascript警报。

<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? 这是因为我试图在div负载中运行javascript吗? I would have thought that was a common requirement. 我会认为这是一个普遍的要求。

Any ideas? 有任何想法吗?

==== Including files ===== ====包含文件=====

index.php 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 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. 正如一些评论者所指出的那样,通过设置DOM节点的innerHTML属性将HTML注入页面时,AJAX响应中的<script>不会执行。 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. AJAX调用的“成功”处理程序应包含运行AJAX后所需的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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