用户输入一些内容,然后程序使用 ajax 向用户输出一些内容。这主要是有效的,问题是通过参数将变量从我的脚本传递到远程函数。
当我将文本作为参数传入时,setTimeout
调用出错了。但是当我在 setTimeout
函数本身中输入它时,它起作用了:
function handleServerResponse(text){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML; //izvlaci se xml sto smo dobili
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById('underInput').innerHTML = message;
setTimeout("process(text)", 1000);
}else{
alert('Someting went wrong !');
}
}
}
完整代码:
<script type = "text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
} else {
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Cant create that object !")
else
return xmlHttp;
}
function process(text){
//text = 'userInput';
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById(text).value);
xmlHttp.open("GET", 'foodstore.php'+"?food="+food,true);
xmlHttp.onreadystatechange = function() {
handleServerResponse(text);
};
xmlHttp.send(null);
}else{
setTimeout("process(text)",1000);//cekaj 1s pa probaj opet
}
}
function handleServerResponse(text){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML; //izvlaci se xml sto smo dobili
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById('underInput').innerHTML = message;
setTimeout("process(text)", 1000);
}else{
alert('Someting went wrong !');
}
}
}
</script>
//*******************************************
<html>
<body onload = "process('userInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
最佳答案
当您将字符串传递给 setTimeout
时,它会在全局范围内进行评估。没有全局 text
变量,因此调用将失败。而是传递一个函数:
setTimeout(function() {
process(text);
}, 1000);
关于javascript - 传递参数时 AJAX setTimeout 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585910/