JavaScript 未使用 Ajax 执行



如何使javascript代码在以前从ajax调用加载的php页面上执行?

代码示例:ajax+function parseScript 强制 javascript 在 ajax 请求的页面上运行

Senario:我正在从selectQuest中选择一個問題.php並使用ajax它請求一個名為showRecord.php的頁面。

页面 showRecord.php 将显示一个表格,其中包含与所选 quetsion 对应的信息。它包含不运行的javascript。javascript 返回将允许我在单击提交时更新数据库中的信息。

下面的代码示例可以在showRecord.php中找到。最后,如果后者运行,showRecord将发出另一个ajax请求updateQuestion.php。

但是javascript没有在showRecord中运行.php

  function show(fileTex,aTex,bTex,cTex,dTex,eTex,newQuestNumTex,textAreaTex,textQuesAnsTex)
    {
  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)
    {
    var resp=xmlhttp.responseText;
    document.getElementById("txtHint2").innerHTML=resp;
    parseScript(resp);
  // document.getElementById("txtHint").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("POST","updateQuestionAdmin.php?param="+fileTex+"&text_A="+aTex+"&text_B="+bTex+"&text_C="+cTex+"&text_D="+dTex+"&text_E="+eTex+"&text_ID="+newQuestNumTex+"&text_Ques="+textAreaTex+"&text_Ans="+textQuesAnsTex,true);
xmlhttp.send();
}
// this function create an Array that contains the JS code of every <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
  var scripts = new Array();         // Array which will store the script's code
  // Strip out tags
  while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
    var s = strcode.indexOf("<script");
    var s_e = strcode.indexOf(">", s);
    var e = strcode.indexOf("</script", s);
    var e_e = strcode.indexOf(">", e);
    // Add to scripts array
    scripts.push(strcode.substring(s_e+1, e));
    // Strip from strcode
    strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
  }
  // Loop through every script collected and eval it
  for(var i=0; i<scripts.length; i++) {
    try {
      eval(scripts[i]);
    }
    catch(ex) {
      // do what you want here when a script fails
    }
  }
}
</script>  

正如iyrag所说,Javascript框架会有所帮助。 jQuery有一个回调函数,你可以在脚本成功加载并使用ajax完成时运行。

您需要在该回调函数中执行其他一些内容,例如:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('#result').html(data); // Display script return on some div
    someFunction(); // blabla
// Execute some other javascript here, you'll be abble to access the DOM of the test.html
// page because here you'lle be sure that test.html is loaded.showRecord.php should not contain javascript, which would rather be here
  }
});

我也发布了这个,因为标签具有jQuery...

最新更新