我正在调用 2 个 JS 函数(Ajax),每个函数都从服务器返回数据。但是第二个函数获取第一个函数的响应文本。
我观察到的一件事是,如果我在使用它之前在函数中使用 1 个或多个警报(以了解数据是什么)(打印图像并显示 anchor ),它的工作原理如下 - 给定一点延迟(我猜)它工作正常,没有延迟它就会失败。
我发现这很奇怪,一旦我做了一些搜索,发现了这篇文章(http://forums.devnetwork.net/viewtopic.php?f=13&t=117523),其中他有一个解决方法 - 给出 1 或 0.5 秒的超时,事情就会正常。
虽然解决方法似乎可以完成工作,但我很好奇为什么响应文本从以前的 Ajax 获取值。
我知道代码不是必需的。但是,以防万一 - 下面给出
胃肠道间质瘤:
1.包含警报时 - 代码工作正常
2.当警报被删除时, anchor 会被显示,但图像不是 splinter 的图像(有点像撕碎的纸片图像),在检查图像信息时我是否找到了上一个函数的数据 - 因此不是正在显示。
<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>
最佳答案
您在每个函数中使用全局变量 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>
关于JavaScript : ResponseText values getting Mixed up?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975585/