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)

我想执行一个从服务器通过AJAX请求发送的函数。函数体不在调用页面中。例如:(完整代码如下)

1.calling PHP script:

1.调用PHP脚本:

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

2.ajax_js2.php脚本:

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

我知道在调用脚本中放置“test”的函数定义就行了。但我想把它放在第二个脚本中。我该怎么办?服务器返回span作为对客户端的响应。在单击跨度“Test AJAX”时,应调用该函数。

1 个解决方案

#1


7

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

除非运行eval(),否则不会执行插入DOM的

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

因此,在您的情况下,当您尝试单击span时,test()将是未定义的,因为脚本代码尚未执行(因此从未定义测试函数)。

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

您可以使用类似的东西来解决它(在DOM注入之后):

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)

(p.s.eval并不邪恶)

更多相关文章

  1. php 基本的常用字符串函数
  2. PHP常用函数归类总结【大全】
  3. php mail函数一段好的代码
  4. C#,PHP对应加密函数
  5. AJAX调用在JavaScript中运行PHP脚本
  6. php计算几分钟前、几小时前、几天前的几个函数
  7. PHP打印输出数组内容及结构函数print_r与var_dump
  8. 通过Bash脚本语言逃避MYSQL命令行。
  9. 是否可以从另一个sql脚本中的存储过程调用sql脚本?

随机推荐

  1. Android 滑动侧边栏(Sliding Menu)第一种实
  2. Android应用程序怎么刷到手机上
  3. Android Studio 单刷《第一行代码》系列
  4. [APK破解]终极狂飙3D漂移,无限金钱,解锁全
  5. Android属性gravity与layout_gravity的区
  6. RelativeLayout布局用到的主要属性
  7. Android Studio 单刷《第一行代码》系列
  8. Android Studio 单刷《第一行代码》系列
  9. 在android平台上如何实现H264解码
  10. Android 打包签名