如何从ajax加载的html文件加载jscript

How can I load jscript from ajax loaded html file?

本文关键字:加载 html 文件 jscript ajax      更新时间:2023-09-26

我有一个html文件(index.html),其中有一个空的div,它使用ajax从另一个html文件(second.html)加载内容。

我正在使用jqueryui加载一个弹出窗口,其中包含一个音频播放器,用于点击index.html上的按钮

当我在index.html上有了下面这样的所有编码时,它工作得很好,并在点击按钮时在弹出窗口上显示音频播放器。-jsfiddle此处

<html>
<head>
  <script type="text/javascript">
       $(function audioplay() {
    $( "#audio" ).dialog({
      autoOpen: false,
        modal: true,
        height: 100,
        width: 335,
      show: {
        effect: "blind",
        duration: 300
      },
      hide: {
        effect: "blind",
        duration: 300
      }
    });
    $( "#opener" ).click(function() {
      $( "#audio" ).dialog( "open" );
    });
  });
  </script>
</head>
<body>
<div id="stuff">
     <div id="audio" title="Places Are Connected">
         <audio controls autoplay>
           <source src="media/1.mp3" type="audio/mpeg">
           Your browser does not support this audio format.
         </audio>
     </div>
<button id="opener">Open Popup</button>
</div>
</body>
</html>

然而,当我从second.html文件加载"stuff"中的内容时,它无法正常工作。例如:

index.html

<body onload="loadXMLDoc()">
 <div id="stuff">
   <!--content from second.html loads here-->
 </div>
</body>
<script>
function loadXMLDoc(){
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("stuff").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","second.html",true);
xmlhttp.send();
}

second.html

<div id="stuff">
 <div id="audio" title="Places Are Connected">
     <audio controls>
       <source src="http://www.hipstrumentals.com/wp-content/uploads/2014/02/Katy-Perry-Ft.-Juicy-J-Dark-Horse-Instrumental-Prod.-By-Dr.-Luke-Max-Martin-Cirkut.mp3" type="audio/mpeg">
       Your browser does not support this audio format.
     </audio>
 </div>
<button id="opener">Open Popup</button>
</div>

.JS文件

$(function() {
$( "#audio" ).dialog({
  autoOpen: false,
    modal: true,
    height: 100,
    width: 335,
  show: {
    effect: "blind",
    duration: 300
  },
  hide: {
    effect: "blind",
    duration: 300
  }
});
$( "#opener" ).click(function() {
  $( "#audio" ).dialog( "open" );
});
});

当我像上面的例子一样使用它时,音频播放器只是显示在索引页面上。按钮出现在播放器下方,什么也不做。

我尝试了很多方法来尝试用ajax加载JS,但到目前为止都没有成功。由于我是JS和ajax的新手,我怀疑可能缺少一个简单的修复方法。因此,如果能帮助它正常工作,我们将不胜感激。

我不清楚你关于通过AJAX加载JavaScript的意思,因为你试图加载的代码不包含任何JS。然而,至于为什么音频播放器没有像你期望的那样出现,问题的第一部分似乎是你在index.html中没有ID为"nonen"的div(或其他元素)。你也不需要重复second.html中"stuff"div的定义。

因此,我将删除second.html的第一行和最后一行,并将onreadystatechange函数更改为包含

document.getElementById("stuff").innerHTML=xmlhttp.responseText;

或者,由于您已经在使用jQuery,我建议您使用内置的AJAX例程。此外,根据您想要的效果,我怀疑您应该在添加第二个div之后(或者每次加载之后,如果稍后再次更改)调用jQuery UI对话框例程

例如,您当前的脚本可以替换为类似以下(未测试的)代码。首先,您需要确保audioPlay()可以在AJAX调用完成后的稍后时间调用,并且它不会在页面加载时立即执行,甚至在第一次调用完成之前。

audioPlay = function () { // Define a function to be called multiple times later
  $('#audio').dialog({
    ... // Fill in your options
  });
  $('#opener').click(function () {
    $('#audio').dialog('open');
  });
};

接下来,您希望loadXMLDoc()函数在加载的HTML插入DOM后调用audioPlay()

loadXMLDoc = function () {
  $('#audio').dialog('destroy'); // Get rid of any existing dialog
  $.ajax({
    dataType: 'html', // Load some HTML data via AJAX
    url: 'second.html', // From this file (relative URL)
    success: function (data) { // When the HTML has finished being downloaded...
      $('#stuff').innerHTML(data); // ...add it to the div with ID "stuff"
      audioPlay(); // ...and create a dialog for the new div
    }
  });
};

好的,修好了。正如我所料,这是一个简单的解决方案。只需要制作一个runPopupJs()函数并在onload时调用它。

function runPopupJs() {
 var head = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'js/popup.js';
 head.appendChild(script);
}

由调用

<body onload="loadXMLDoc();runPopupJs()">