javascript未执行插入内部HTML

时间:2014-05-14 16:28:48

标签: javascript ajax

我试图通过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);
 ?>

1 个答案:

答案 0 :(得分:0)

在运行时作为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();