ajax 异步处理 Get请求
Posted @binglong180
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax 异步处理 Get请求相关的知识,希望对你有一定的参考价值。
1、js的编写
var xmlHttpRequest = null; //1、创建XMLHttpRequest对象 if (window.XMLHttpRequest) {//新版本返回为TRUE xmlHttpRequest = new XMLHttpRequest(); } else { xmlHttpRequest = new ActiveXObject( "Microsoft.XMLHTTF"); } //2、设置回调函数 xmlHttpRequest.onreadystatechange = callBack; var username = $("#username").val(); //3、初始化XMLHttpRequest组件 var url = "UserServlet?username=" + username; xmlHttpRequest.open("GET", url, true); //4、发送请求 xmlHttpRequest.send(null); //回调函数callBack的编写 function callBack() { if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { var data = xmlHttpRequest.responseText; if (data == "true") { $("#errMsg").html("用户名已被注册"); } else { $("#errMsg").html("用户可以注册"); } } } });
2、servlet的编写
package com.niu.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String name = req.getParameter("username"); boolean used = false; if ("ajax".equals(name)) { used = true; } resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.print(used); out.flush(); out.close(); } }
以上是关于ajax 异步处理 Get请求的主要内容,如果未能解决你的问题,请参考以下文章
jquery 之ajax,get,post异步请求简单代码模版
PHP. 02®. Ajax异步处理常见的响应状态XMLHttpRequest对象及APIajax的get/post方法