代码之家  ›  专栏  ›  技术社区  ›  Dutchie432

尝试调用从Ajax调用返回的JS代码

  •  0
  • Dutchie432  · 技术社区  · 14 年前

    好吧,我有一个javascript函数来检索一些HTML…

    function updateQuestions(i){
        var url = 'getQuestions.php?sys=' + i;
        if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
            receiveReq.open("GET", url, true);
            receiveReq.onreadystatechange = handleQuestionsUpdate; 
            receiveReq.send(null);
        }
    }
    
    function handleQuestionsUpdate() {
        if (receiveReq.readyState == 4) {
            var a=receiveReq.responseText;
            document.getElementById('questions').innerHTML=a;
            checkSpeakers(); //Error Occurs Here, even though checkSpeakers() is a function in the returned HTML chunk.
        }   
    }
    

    这个HTML不仅仅是HTML,更具体地说,它是一个表单和一块JavaScript。javascript硬编码为HTML,不被<script src=“.”>引用。

    调用时无法识别检索到的JS代码是否正常?如果是这样的话,如果每次DIV更新时都需要JS进行更改,那么我的选择是什么?

    这是返回到javascript函数的文本。

    function checkPillowSpeakers()
    {
        var pillowSpeakers = document.getElementById('Q9').value + document.getElementById('Q10').value;
        document.getElementById('PS1').style.display = ((pillowSpeakers > 0)? '' : 'none');
        document.getElementById('PS2').style.display = ((pillowSpeakers > 0)? '' : 'none');
    }~ARRAYSEPERATOR~<html>....</html>
    

    JS代码通过~arraysperator~标记与HTML代码分离。问题是我现在不想执行代码,我只想让它排队,这样我就可以按命令调用它。

    5 回复  |  直到 12 年前
        1
  •  1
  •   streetparade    14 年前

    您应该首先尝试从HTML内容中获取JavaScript部分。 然后您可以使用 eval() 来自javascript的函数;

        2
  •  1
  •   Community kgiannakakis    7 年前

    我的答案 How To Call Javascript In Ajax Response? IE: Close a form div upon success

    // response is the data returned from the server
    var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
    var reScript = /\<script.*?>(.*)<\/script>/mg;
    response = response.replace(reScript, function(m,m1) {
        var fn = new Function(m1); // this will make the eval run in the global scope
        fn(); //will run alert("foo");
        return "";
    });
    alert(response); // will alert "htmlhtml"
    
        3
  •  1
  •   Dutchie432    14 年前

    在做了大量的研究之后,eval()似乎有一些内存问题…所以我发现了这个解决方案:

    //Firstly, create a div called codeHolder
    
    var javascriptCode="function test(){.....}";
    var JSONCode=document.createElement("script");
    JSONCode.setAttribute("type","text/javascript");
    JSONCode.text=javascriptCode;
    
    var cell=document.getElementById("codeHolder");
    if ( cell.hasChildNodes() )
        while ( cell.childNodes.length >= 1 )
            cell.removeChild( cell.firstChild );
    
    cell.appendChild(JSONCode);
    
        4
  •  0
  •   oezi    14 年前

    你真的应该考虑为Ajax使用JSlib来实现浏览器兼容性和更少的内存泄漏——但是如果你想自己做这件事,你必须在使用之前先对返回的javascript进行eval()。

        5
  •  0
  •   bfavaretto    12 年前

    也有 responseXML :

    receiveReq.responseXML.getElementsByTagName('input')
    

    等。