【发布时间】:2015-10-07 06:50:26
【问题描述】:
我正在学习承诺,所以我创建了一个通过 ajax 生成内容的简单网站。
当用户点击链接时,它会改变网站的内容,但首先它应该淡出原始内容。
我已经编写了调用承诺并返回内容的脚本
function getcontent(url){
return new Promise(function(resolve,reject){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload=function(){
if(xhttp.status==200){
resolve(xhttp.response)
}
else{
reject(Error(xhttp.responseText))
}
}
xhttp.send();
})
}
以及应该添加内容的函数
function change(url){
var doc=document.getElementsByClassName("info")[0];
return getcontent(url).then(function(x){
doc.children[0].classList.add("remove");
return x
}).then(function(x){
doc.removeChild(doc.children[doc.children.length-1]);
var div=document.createElement("div");
div.innerHTML=x;
doc.appendChild(div)
})
}
更清楚一点,要添加类的元素有
-webkit-transition:15s ease all;
所以我想,让原始内容淡出,然后将 ajax 内容添加到网站。这就是我使用承诺的原因。我认为承诺链接等待 .then() 方法完成,然后执行下一个 .then() 方法。但是在原始内容消失之前将 ajax 内容添加到站点,因此在第一个 .then() 方法完成之前调用它。我错过了什么?
我尝试在两个单独的函数中使用 ontransitionend 事件作为评论建议,但它不起作用
function getcontent(url){
return new Promise(function(resolve,reject){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload=function(){
if(xhttp.status==200){
resolve(xhttp.response)
}
else{
reject(Error(xhttp.responseText))
}
}
xhttp.send();
})
}
function change(url){
var doc=document.getElementsByClassName("info")[0];
getcontent(url).then(function(x){
return new Promise(function(res,rej){
doc.addEventListener("transitionend",function(){
res(x);
})});
doc.children[0].classList.add("remove")
})
}
【问题讨论】:
标签: javascript ajax promise