javascript不执行插入的内部HTML

javascript is not executing inserted in inner HTML

本文关键字:内部 HTML 插入 执行 javascript      更新时间:2023-09-26

我试图通过ajax请求从另一个页面获得响应,例如它的名称是ajaxresponse.php,我还想在该ajaxresponse.php页面上执行java脚本完成的一些操作,但js代码不工作。我从该页得到的响应,但该页的js代码不工作。我想只知道为什么ajax代码在我的第二页不工作?

function ajaxinput(tinnerid)
{
    var xmllhttp;
       if (window.XMLHttpRequest)
        {
          xmlhttp=new XMLHttpRequest();
        }
       else
        {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
       xmlhttp.onreadystatechange=function()
        {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
           {
            document.getElementById("articledive").innerHTML=xmlhttp.responseText;
           }
        }
    xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
    xmlhttp.send();
}
下面是第一页 的php代码
<?php
 $con1=mysqli_connect("127.0.0.1","root","root","databasetry");
 $result=mysqli_query($con1,"select title,articleid  from article");
 $tinnerid=0;
 $articledivid=0;
   while($row = mysqli_fetch_array($result))
    {
     $tinnerid=$row['articleid'];
     echo "<div class='tinner' id='$tinnerid' onclick='ajaxinput($tinnerid)'    style='cursor:pointer;'>";
     echo"<span class='fontdiv'>";
     echo $row['title']."<br>";
     echo "</span>";
     echo"</div>";
     $tinnerid++;
     $articledivid++;
    }
 mysqli_close($con1);
?>
这是第二页的js代码
function run()
{
 alert("example");
}

第二页的php代码

 <?php
  $id=$_GET['q'];
  $result=mysqli_query($con1,"select user.username,article.articleid,article.title,article.artiletext from article inner join user on article.user_id=user.user_id where article.articleid=$id");
 $divid=0;
    while($row = mysqli_fetch_array($result))
     {   
      $id=0; 
      echo"<div class='inner' id=$divid >";
      $id=$row['articleid'];
      echo "<font class='ftitle'>"."Title : "."<a href='#'onclick='ajaxinput($id)'>".$row['title']."</a>"."</font>"."<br>"."<font class='ftext'>".$row['artiletext']."</font>"."<br>"."<font class='flast'>"."Posted By : ".$row['username']."</br>"."</font>"."<br>"."<br>";    
      echo "<button type='button' onclick='con($id)'  class='button'><font size='1'>Delete</font></button>";
      echo"</div>";
      $divid++;
      echo"<script>run()</script>";   
      }
  mysqli_close($con1);
 ?>

在运行时作为innerHTML插入的Javascript不会被执行。一个可能的解决方案是从第二页返回中删除脚本标记,并在ajax回调后在第一页上调用方法run()。这样的:

function ajaxinput(tinnerid)
{
   var xmllhttp;
   if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
    }
   else
    {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
        document.getElementById("articledive").innerHTML=xmlhttp.responseText;
        /* CALL IT HERE AFTER INSERT */
        run();
       }
    }
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();