2009-09-15 40 views
3

这是我的代码。看到注释掉的那一行。当元素ID(这是一个范围)是硬编码的,它的工作原理。当通过连接传递给stateChanged的变量创建id时,它不起作用。我不允许将变量传递给stateChanged吗?怎么了?在xmlhttp.onreadystatechange函数中,如何传递要编辑的ID的名称?

function multiplePassportPoints(id, counter) 
{ 
xmlhttp=GetXmlHttpObject(); 
if (xmlhttp==null) 
{ 
alert ("Browser does not support HTTP Request"); 
return; 
} 
var url="addmorepoints.php"; 
url=url+"?id="+id+"&c="+counter; 
url=url+"&sid="+Math.random(); 

xmlhttp.onreadystatechange=stateChanged(id,counter); 
xmlhttp.open("GET",url,true); 
xmlhttp.send(null); 
} 

function stateChanged(id, counter) 
{ 
    if (xmlhttp.readyState==4) 
    { 
    //THIS WORKS (assuming id is 99 and counter is 5: 
    //document.getElementById("99_5").innerHTML += xmlhttp.responseText; 

    //BUT I NEED IT TO WORK LIKE THIS: 
    document.getElementById(studentID+"_"+counter).innerHTML += xmlhttp.responseText; 
    } 
} 

谢谢!

回答

8

您可以更改代码以这种

xmlhttp.onreadystatechange = function() { 
     stateChanged(id,counter); 
    };  
+0

岩石上!有用!谢谢。 – Jen 2009-09-15 06:06:01

+6

+1。但是我希望你能解释一下'xmlhttp.onreadystatechange = stateChanged(id,counter);'实际上是调用'stateChanged(id,counter)',并将返回值赋给'onreadystatechange'而不是分配函数本身。 – 2009-09-15 15:57:51

0

一个更好的方法,可以将前面的调用完成之前多次调用。请注意,如果您多次调用multiplePassportPoints,则以前的xmlhttp值将被覆盖。有两个结果:
1-没有发生并发时一切正常(很可能),
2-第一次调用从不发生(很低的可能性,但它会不时发生,将很难发现和重现)

但下面的代码使用局部变量,并且可能(未测试)可以安全地反复调用。

function multiplePassportPoints(id, counter) { 
    var xmlhttp=GetXmlHttpObject(); 
    if (xmlhttp==null) 
    { 
    alert ("Browser does not support HTTP Request"); 
    return; 
    } 

    var url="addmorepoints.php"; 
    url=url+"?id="+id+"&c="+counter; 
    url=url+"&sid="+Math.random(); 

    xmlhttp.onreadystatechange=function() { 
    if (xmlhttp.readyState==4) { 
     stateChanged(id, data, xmlhttp.responseText); 
    } 
    }; 

    xmlhttp.open("GET",url,true); 
    xmlhttp.send(null); 
} 

function stateChanged(id, counter,text) 
{ 
    document.getElementById(id+"_"+counter).innerHTML += text; 
} 
1
<script type="text/javascript"> 
var i=1; 
function validate(str) 
{ 
xmlHttp=GetXmlHttpObject() 
var url="checkvalidate.php" 
url=url+"?User9="+str 
xmlHttp.onreadystatechange=stateChanged19 
xmlHttp.open("GET",url,true) 
xmlHttp.send(null) 
} 
function stateChanged19() 
{ 

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") 
    { 

    document.getElementById("valid"+i) 
    .innerHTML=xmlHttp.responseText 
    i=i+1; 
    } } 
</script> 
相关问题