標籤:asc tle java html btn str script 請求 odi
一、ajax.js
function ajax(url, fnSucc, fnFaild) { // 1、建立ajax var oAjax = null; if (window.XMLHttpRequest) { var oAjax = new XMLHttpRequest(); } else { var oAjax = new ActiveXObject("Microsoft.XMLHTTP"); } //2 串連伺服器 oAjax.open(‘GET‘, url, true); //3發送請求 oAjax.send(); //4接收返回 oAjax.onreadystatechange = function() { if (oAjax.readyState == 4) { //完成 if (oAjax.status == 200) { //成功 fnSucc(oAjax.responseText); } else { if (fnFaild) { fnFaild(); } } } }}
二、執行個體一--無重新整理讀取檔案
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax</title> <script src="ajax.js"></script> <script> //無重新整理資料讀取,ajax window.onload = function() { var oBtn = document.getElementById(‘btn1‘) oBtn.onclick = function() { ajax(‘txt1.txt‘, function(str) { alert(str); }) } } </script></head><body> 點擊後讀取txt1.txt<br/> <input id="btn1" type="button" name="" value="讀取"></body></html>
三、執行個體二--簡單分頁
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>簡單分頁</title> <style> #div1 { width: 400px; height: 300px; background: #ccc; border: 1px solid red; } </style> <script src="ajax.js"></script> <script> window.onload = function() { var aBtn = document.getElementsByTagName(‘input‘); var oDiv = document.getElementById(‘div1‘); var i = 0; for (i = 0; i < aBtn.length; i++) { aBtn[i].index = i; aBtn[i].onclick = function() { ajax(this.index + 1 + ‘.txt‘, function(str) { oDiv.innerHTML = str; }) } } } </script></head><body> <input type="button" name="" value="按鈕1"> <input type="button" name="" value="按鈕2"> <input type="button" name="" value="按鈕3"> <div id="div1"> </div></body></html>
javascript中級--ajax(1)