demo1
来源:互联网 发布:ubuntu 硬盘测速 编辑:程序博客网 时间:2024/06/02 12:17
AJAX(异步的JavaScript与XML)缺点:不能使用浏览器的“前进”,“后退”来回退或恢复Ajax的操作。XMLHttpRequest对象,微软IE核心使用ActiveX实现,其他浏览器使用其他技术实现此对象。使用范例: var xmlHttpRequest = null; if(window.activeXObject)//除undefined和null外均是true;IE浏览器里此项为真 { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest)//除IE外的浏览器实现了此对象 { xmlHttpRequest = new XMLHttpRequest(); } if(null != xmlHttpRequest) { xmlHttpRequest.open("GET",url,true);//true表示以异步的方式发送请求,一般均为true。在firefox中,此项设为false后,下面的回调方法注册失效。 xmlHttpRequest.onreadystatechange=myfun;//注册回调方法,myfun为自定义的方法。 xmlHttpRequest.send(null);//若为POST方式,此方法可接受需提交的参数名值对字符串.如xmlHttpRequest.send("name=zhao&age=22"); } function myfun()//一旦状态发生变化即调用此方法 { if(xmlHttpRequest.readyState == 4)//收到响应 { if(xmlHttpRequest.status == 200)//客户端完整收到响应 { alert(xmlHttpRequest.responseText); } } } 若以POST方式提交,在send之前,需执行:xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");jquery实现AJAX: $.ajax({ type:"POST",//请求类型,GET或POST url:"myServlet",//远程URL dataType:"html",//返回的数据类型,有xml、json和html(即文本)。可选,默认是html。 data:{"param1":$("#text1").val()},//提交的参数,可选 success:function(returnedData){//回调方法 alert(returnedData); } }); 返回XML: 在服务器端: import org.dom4j.*; ...//其他代码 Document doc = DocumentHelper.createDocument(); Element rootElement = doc.addElement("users"); Element userElement = rootElement.addElement("user"); Element nameElement = userElement.add("name"); nameElement.setText("zhao"); response.setContentType("text/xml,charset=utf-8"); response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); PrintWriter out = response.getWriter(); OutputFormat format =OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter xmlWriter = new xmlWriter(out,format); xmlWriter.writer(doc); out.flush(); 客户端: $.ajax({ type:"POST",//请求类型,GET或POST url:"myServlet",//远程URL dataType:"xml",//返回的数据类型,有xml、json和html(即文本)。可选,默认是html。 data:{"param1":$("#text1").val()},//提交的参数,可选 success:function(returnedData){//回调方法 var id = $(returnedData).find("name").text(); } }); 返回JSON: 服务器端: Person p1 = new Person("zhao"); Person p2 = new Person("li"); ArrayList<Person> list = new ArrayList<Person>(); list.add(p1); list.add(p2); Gson gson = new Gson(); String json = gson.toJson(list); response.setContentType("application/json;charset=utf-8"); response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); PrintWriter out = response.getWriter(); out.print(json); out.flush(); 客户端: $.get("getServlet",{},function(returnedData,status){ var html = "<table>"; for(var i=0;i<returnedData.length;i++){ var people returnedData[i]; var name = people.name; html+="<tr><td>name:</td><td>"+name+"</td></tr>"; } html+="</table>"; $("theBody table:eq(0)").remove(); $("theBody").append(html); });