dshgnt2008 2013-09-06 11:18
浏览 45
已采纳

在通过AJAX响应发送的页面上执行javascript函数

I want to execute a function that is sent over AJAX request from the server. The function body isn't in the calling page. For example: (the complete code is given below)

1.calling PHP script:

<script>
 function fun()
 {
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }  
 ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){

            document.getElementById("rslt").innerHTML = ajaxRequest.responseText;


        }
    }

    ajaxRequest.open("GET", "ajax_js2.php", true);
    ajaxRequest.send(null);

 }
</script>
<input type="button" onclick="fun()">
<div id="rslt">
</div>

2.ajax_js2.php script:

<script>
 function test()
 {
   alert("Hello");
 }
</script>
<span onclick="test()">Test AJAX</span>

I know putting the function definition of "test" in the calling script will do. But I want to keep it in the second script.What should I do ? The server returns the span as a response to the client. While clicking upon the span "Test AJAX" the function should be called.

  • 写回答

1条回答 默认 最新

  • doutuoshou8915 2013-09-06 11:27
    关注

    <script> tags inserted into the DOM will not be executed, unless you run eval(). Read more here: Can scripts be inserted with innerHTML?

    So in your case, test() will be undefined when you try to click on the span because the script code has not been executed (thus never defined the test function).

    You can get around it using something like this (after the DOM injection):

    var scripts = document.getElementById("rslt").getElementsByTagName("script");
    for( var i=0; i<scripts.length; i++ ) {
        eval(scripts[i].innerText);
    }
    

    (p.s. eval is not evil)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择