Ajax get方式向服务器发送请求:
<script type="text/javascript"> //创建XMLHttpReques对象 function createXMLHttpRequest(){ if(window.XMLHttpRequest){ //Mozilla浏览器 XMLHttpReq=new XMLHttpRequest(); }else{ //IE浏览器 if(window.ActiveXObject){ try{ XMLHttpReq=new ActionXObject("Msxm12.XMLHTTP"); }catch(e){ try{ XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){} } } } } //处理服务器响应结果 function handleResponse() { // 判断对象状态 if (XMLHttpReq.readyState == 4) { // 信息已经成功返回,开始处理信息 if (XMLHttpReq.status == 200) { var out = ""; var res = XMLHttpReq.responseXML; var response= res.getElementsByTagName("response")[0].firstChild.nodeValue; //5. 解析服务器返回的信息,更新用户界面 document.getElementById("Hello").innerHTML = response; } } } //发送客户端的请求 function sendRequest(url){ //1.创建XMLHttpRequest createXMLHttpRequest(); //2.设置回调函数 XMLHttpReq.onreadystatechange=handleResponse; //3.初始化XMLHttpRequest组建并发送请求 XMLHttpReq.open("GET",url,true); //发送请求 XMLHttpReq.send(null); //post请求时把GET,改为POST,还要加上 //XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); //把请求的参数写在XMLHttpReq.send(key=value);中 } //开始调用Ajax的功能 function sayHello() { var name=document.getElementById("name").value; //发送请求 sendRequest("SayHell?name="+name); } </script>
post方式向服务器发送请求时候要添加上:
var name = document.getElementById("name").value;
XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
XMLHttpReq.send("name="+name);
index.jsp页面:
<body> <input type = "text" name = "name" id = "name" onblur = "sayhello();"/> <div id = "Hello"></div> </body>
servlet代码片段:
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/xml;charset=UTF-8"); response.setHeader("Cache-Control","no-cache"); String name = request.getParameter("name"); System.out.println(name); PrintWriter out = response.getWriter(); out.println(name); out.close(); }原文链接:https://www.f2er.com/ajax/166020.html