在通过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)
我想执行一个从服务器通过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并不邪恶)
更多相关文章
- php 基本的常用字符串函数
- PHP常用函数归类总结【大全】
- php mail函数一段好的代码
- C#,PHP对应加密函数
- AJAX调用在JavaScript中运行PHP脚本
- php计算几分钟前、几小时前、几天前的几个函数
- PHP打印输出数组内容及结构函数print_r与var_dump
- 通过Bash脚本语言逃避MYSQL命令行。
- 是否可以从另一个sql脚本中的存储过程调用sql脚本?