使用ajax的4大步骤
1.根据不同的浏览器 创建XMLHttpResponse对象
2.准备发送的相关参数 1发送方式(get/post) 2发送地址url(当get请求时,url包含相关的参数) 3同步异步方式
3.send发送的内容 (get发送send为null post发送时要设置请求头,及请求主题)
4.回调函数的设置(onreadystatechange / readystate / status)判断文件类型(xml/text)
<body> <script type="text/javascript"> <!-- data = { data: "", dataType: "xml/jsop", type: "get/post", url: "", asyn: "true/false", success: function () { }, failure: function () { } }--> <!--封装的ajax--> function ajax(data) { //1.创建xhr对象\ var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // 准备发送前的一些配置参数 var type = data.type == 'get' ? 'get' : 'post'; var url = ''; if (data.url) { url = data.url; if (type == 'get') { url += "?" + data.data + "&_t=" + new Date().getTime(); alert(data.data); } } var flag = data.async == 'true' ? 'true' : 'false'; xhr.open(type, url, flag); //3.send if (type == 'get') { xhr.send(null); } else if (type == 'post') { xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.send(data.data); } // 4.回调函数 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (typeof data.success == 'function') { var d = data.dataType == 'xml' ? xhr.responseXML : xhr.responseText; data.success(d); } else { if (typeof data.failure == 'function') { data.failure(); } } } } } //ajax封装函数的使用 window.onload原生的javascript使用 window.onload = function () { var btn = document.getElementById('btn'); btn.onclick = function () { var param = { url: "ajaxJsp.jsp", type: 'get', dataType: 'json', success: function (data) { alert(data); } }; ajax(param); } } </script> <div id="ems"> <div> <input type="text" id="code"> <input type="button" value="查询" id="btn"> </div> <div id="list"></div> </div> </body>