将加载gif添加到简单脚本

我真的是Javascript的新手,但我有这个脚本加载url的内容,一切正常。 我在一个按钮上使用onClick方法调用plannerSpin函数,但是如何在显示动画gif的同时进行所有这些操作?

var xmlHttp function plannerSpin(str) { xmlHttp = GetXmlHttpObject() if (xmlHttp == null) { alert("Browser does not support HTTP Request") return } var url = "/recipes/planner/data" xmlHttp.onreadystatechange = stateChanged xmlHttp.open("GET", url, true) xmlHttp.send(null) } function stateChanged() { if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") { document.getElementById("recipe_planner_container").innerHTML = xmlHttp.responseText } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } 

有很多方法……例如:你可以隐藏图像:

  

并在您启动AJAX请求时立即显示:

 document.getElementById('loading').style.display = 'inline'; 

然后,在请求完成后再次隐藏图像:

 if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){ document.getElementById('loading').style.display = 'none'; document.getElementById("recipe_planner_container").innerHTML = xmlHttp.responseText; } 

或者,您可以使用jQuery,Prototype,Mootools或任何您想要的JS库。

再见!

您可以在plannerSpin的开头添加加载gif,并在stateChanged函数中删除。 Somethig喜欢:

 var img; function plannerSpin(str) { img=document.createElement("img"); img.src="image/path"; //Here you can set some style for the image like an absolute position document.body.appendChild(img); .... } function stateChanged() { ... document.body.removeChild(img); }