2012-11-18 51 views
2

如何使JavaScript代码执行在以前从ajax调用加载的PHP页面?JavaScript不执行与AJAX

代码示例: AJAX +功能parseScript强制的JavaScript的AJAX请求的页面

塞纳里奥上运行:我选择从selectQuest.php一个问题,使用AJAX请求它​​被称为showRecord页.PHP。

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

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

但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> 
+2

我会强烈建议使用一个Javascript框架(如jQuery或Dojo)发出AJAX请求;它会比你在这里有更好的地狱。 – q3d

+0

iyrag任何想法如何强制JavaScript在ajax请求的页面上执行??? –

+0

'updateQuestionAdmin.php'返回哪个脚本?您是否尝试使用浏览器的调试工具浏览JavaScript代码?它是否会与您期望在那里的脚本达成'eval'声明? –

回答

0

正如iyrag说运行,一个JavaScript框架会有所帮助。 jQuery有一个callback function,您可以在脚本成功加载并使用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的...