Javascript学习笔记12——Ajax入门
生活随笔
收集整理的這篇文章主要介紹了
Javascript学习笔记12——Ajax入门
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Ajax:Asynchronous Javascript And XML。寫個簡單的例子:
<body><form id="form1" runat="server">
<div>
<asp:Label ID="LabelTime" runat="server"></asp:Label>
</div>
</form>
<script type="text/javascript">
if (!window.XMLHttpRequest) {
window.XMLHttpRequest = function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
function UpdateClock() {
var request = new XMLHttpRequest();
request.open("post", "TimeTest.aspx", false);
request.send("");
document.getElementById("LabelTime").innerText = request.responseText;
}
setInterval(UpdateClock, 1000);
</script>
</body>
而在另一個頁面寫下當前時間,這樣就形成了一個鐘表。
代碼很簡單,就是操縱一個XMLHttpRequest對象來獲取服務器時間,然后更新時間。上面的代碼在與服務器交互時,并沒有頁面整體刷新,而是局部刷新。
但是上面的代碼在request.open時,最后一個參數為false,表示發出的XMLHttpRequest是同步的,由于Javascript是單線程的,所以在等待請求的過程中,線程會被阻塞,如果請求時間過長,瀏覽器會停止響應。
雖然Javascript是單線程的,但是XMLHttpRequest具備異步處理請求的能力。代碼如下:
<body><form id="form1" runat="server">
<div>
<asp:Label ID="LabelTime" runat="server"></asp:Label>
</div>
</form>
<script type="text/javascript">
if (!window.XMLHttpRequest) {
window.XMLHttpRequest = function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
function AsynRequest() {
var request = new XMLHttpRequest();
request.open("post", "TimeTest.aspx", true);
request.onreadystatechange = function () {
if (request.readyState === 4) {
UpdateClock(request.responseText);
}
};
request.send("");
}
function UpdateClock(time) {
document.getElementById("LabelTime").innerText = time;
}
setInterval(AsynRequest, 1000);
</script>
</body>
哎,沒有智能提示的日子真不好過。
轉載于:https://www.cnblogs.com/kym/archive/2010/01/17/1650229.html
總結
以上是生活随笔為你收集整理的Javascript学习笔记12——Ajax入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 男士美容,这些方面你做了没? - 生活至
- 下一篇: 使用QueueUserAPC线程注入,