2011-08-07 143 views
2

我打电话给2个JS函数(Ajax),每个函数都从服务器返回数据。但第二个函数获取第一个函数的responsetext。我看到的一件事是,如果在使用它(打印图像和显示锚点)之前,我在函数中使用了一个或多个警报(知道数据是什么),它可以正常工作 - 给定了一点延迟(我猜)它的工作正常,没有它失败。Javascript:ResponseText值越来越混淆?

我觉得这很奇怪,一旦我做了一些搜索发现这篇文章(http://forums.devnetwork.net/viewtopic.php?f=13&t=117523),他有一个解决方法 - 给1或0.5秒的超时和事情将是正确的。

虽然解决方法似乎能够完成工作,但我很好奇为什么响应文本正在从之前的Ajax中获取值。

我知道代码是不是necessary.but,以防万一 - 其下方

GIST给出:

1.警报包括当 - 的代码工作正常

2。当警报被删除时,锚点正在显示,但不是图像是检查图像信息时被压碎的图像(撕碎的纸张图像的类别),我发现数据形成了前一个功能 - 因此未被显示。

<style type="text/css"> 
.image{ 
position: relative; 
left: 20%; 
} 
</style> 

<script type="text/javascript" > 
function create(){ 
alert("createUid"); // 1st alert with which the code works 
xmlhttp=new XMLHttpRequest(); 
xmlhttp.onreadystatechange=function(){ 
    if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
    var json = eval(xmlhttp.responseText); 
    for(i=0;i<json.length;i++){  
     var a = document.createElement("a"); //creates a List of anchors 
     a.id="a"+json[i].uid; 
     a.style.display="block"; 
     a.setAttribute("href","#"); 
     a.setAttribute("onclick","alert("+json[i].uid+")"); 
     a.appendChild(document.createTextNode(json[i].uid)); 
     document.getElementById("tag").appendChild(a); 
     } 
    } 
} 
xmlhttp.open("GET","users.php?send=vivek",true); 
xmlhttp.send("NULL"); 

} 
function display(){ 
alert("pict"); 
xmlhttp=new XMLHttpRequest(); 
xmlhttp.onreadystatechange=function(){ 
    if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
     var img = document.createElement("img"); 
     img.id="dispPict"; 
     img.class="image"; 
     img.setAttribute("alt","ViperRules!!");    
     img.setAttribute("src","data:image/jpg;base64,"+xmlhttp.responseText); // response text is a binary of an image stored in the DB. 
     img.style.display="block"; 
     document.body.appendChild(img); 
     //document.getElementById("Tag").appendChild(img); 
     } 
    } 
xmlhttp.open("GET","users.php?pict=vivek",true); 
xmlhttp.send("NULL"); 
} 
</script> 

<body onload=" display(), create();"> 
<div id="tag" class="image"> </div> 
</body> 

回答

2

您在每个函数中使用全局变量xmlhttp - 意味着每个函数都使用相同的xmlhttp。第二个函数调用替换第一个函数的xmlhttp onreadystatechange,所以当第一个调用返回时,它执行第二个onreadystatechange。

要解决此问题,您不需要使用全局变量。这可以通过在定义变量前加上var来完成。

实施例:

<script type="text/javascript" > 
function create(){ 
    alert("createUid"); // 1st alert with which the code works 
    var xmlhttp=new XMLHttpRequest(); 
    ... 
} 

function display(){ 
    alert("pict"); 
    var xmlhttp=new XMLHttpRequest(); 
    ... 
} 
</script> 
+0

@ Janiv:不知道xmlhttp是一个全局变量,明白我出错的地方。谢谢。 –

+0

@Vivek:这不是xmlhttp是JavaScript中的一个预定义的全局变量,只是它在第一次使用时将var留在了它的前面而成为了全局变量。 – janiv

+0

哦..我会记住的。 –

1

全局属性被使用 - xmlhttp。因此,回调里面的xmlhttp而不是在关闭中绑定,而是全局属性是覆盖第二次调用create()。 (超时/延迟允许第一XHR请求来实际光洁度第一)

最简单的 “修复” 是改变:

xmlhttp=new XMLHttpRequest(); 

到:

var xmlhttp=new XMLHttpRequest(); 

这将声明xmlhttp作为函数局部变量,因此它将在回调中关闭。然而,我会推荐使用一个框架 - jQuery非常流行 - 使整个过程更简单。

快乐编码。

+0

谢谢。收获! –