好的,所以我有一个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代码通过~ARRAYSEPERATOR~标记从HTML代码中分离出来。问题是我不想在此时执行代码,我只是想让它排队,所以我可以通过命令调用它。
答案 0 :(得分:1)
您应首先尝试从HTML内容中获取JavaScript部分。
然后,您可以使用JavaScript中的eval()
函数轻松执行它;
答案 1 :(得分:1)
我的答案来自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"
答案 2 :(得分:1)
经过大量的研究后,似乎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);
答案 3 :(得分:0)
你应该考虑使用js-lib for ajax来实现浏览器兼容性和更少的内存泄漏 - 但是如果你想自己这样做,你必须eval()传回的javascript才能使用它。
答案 4 :(得分:0)