日期:2014-05-18 浏览次数:20690 次
<html> <head><title>ajax 异步取数据例子</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> <!-- var req; //ajax入口函数 function getResult() { //这里ajaxGetData是application的名字 var url = "/ajaxGetData/servlet/GetInfoById?id="+escape(document.getElementById('txtID').value); createXMLHttp(); if(req){ req.open("GET",url, true); req.onreadystatechange = complete; req.send(null); } } //建立xmlhttpRequest对象 function createXMLHttp() { if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHttp"); } else if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } } //从服务器取回数据后怎么处理 function complete(){ if (req.readyState == 4) { if (req.status == 200) { document.getElementById('message').innerHTML = req.responseXML.getElementsByTagName("strcontent")[0].firstChild.data; } } } //--> </script> </head> <body> <input type="text" id="txtID" value="" /> <input type="button" id="ajaxButton" value="点击我从服务器取数据" onclick="getResult();"/> <div id = "message"> 这是显示取回信息的地方 </div> </body> </html>
------解决方案--------------------
<html> <head><title>ajax 异步取数据例子</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> <!-- var xmlHttp; //声明xmlhttpRequest对象 function createXMLHttpRequest() //建立xmlhttpRequest对象 { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } function startRequest(url) //发送xmlhttpRequest请求 { createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", url, true); xmlHttp.send(null); } function handleStateChange() //等待返回成功则处理 { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { handleResult(); } } } function handleResult() //从服务器取回数据后怎么处理 { parent.document.getElementById("yourid").innerHTML = xmlHttp.responseText; } function getResult() { index = modified_inbox_list_index; startRequest('your_action.do?id=' + document.getElementById('txtID').value); } //--> </script> </head> <