在通过AJAX响应发送的页面上执行javascript函数 [英] Execute javascript function on a page sent via AJAX response

查看:59
本文介绍了在通过AJAX响应发送的页面上执行javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行通过服务器的AJAX请求发送的功能.函数主体不在调用页面中.例如:(下面提供了完整的代码)

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.调用PHP脚本:

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脚本:

2.ajax_js2.php script:

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

我知道将"test"的函数定义放在调用脚本中即可.但我想将其保留在第二个脚本中.该怎么办?服务器将跨度作为响应返回给客户端.在跨度"Test AJAX"上单击时,应调用该函数.

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.

推荐答案

< script> 标记.>.在此处阅读更多信息:脚本可以插入innerHTML吗?

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

因此,在您的情况下,由于未执行脚本代码(因此从未定义 test 功能).

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).

您可以使用以下方法解决问题(在注入DOM之后):

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);
}

(附上 eval 不是邪恶的)

这篇关于在通过AJAX响应发送的页面上执行javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆