ajax
Posted java-rui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax相关的知识,希望对你有一定的参考价值。
1、原生的
<script type="text/javascript"> window.onload = function(){ var a = document.getElementById("a"); a.onclick = function(){ //创建XMLHttpRequest对象,这是实现异步请求的关键 var request = new XMLHttpRequest(); //设置请求方式,请求路径 var method = "get"; var url = this.href; //准备发送、发送(get方式没有参数,post方式需要准备参数) request.open(method, url); request.send(null); //onreadystatechange检测XMLHttpRequest状态的改变(0-4),4表示完成 request.onreadystatechange = function(){ if(request.readyState == 4){ //检查返回数据是否可用 if(request.status == 200 || request.status == 304){ alert(request.responseText); } } } //取消<a>跳转行为 return false; } } </script>
2、jquery很好的封装了ajax
demo:登录检测用户名是否可用。
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>tets Ajax</title> <script type="text/javascript" src="scripts/jquery-1.7.2.js"></script></head> <script type="text/javascript"> $(function(){ $("input").change(function(){ var userName = $("input").val().trim(); if(userName != "" && userName.length > 0){ var url = "checkUserName"; //json格式 var message={"userName" : userName}; var type = "html"; $.get(url , message , function(data){ $("#info").empty().append($(data)); } , type); } }); }); </script> <body> <form action="" method="post"> 用户名:<input type="text" name="userName"></input> <div id="info"></div> </form> </body> </html>
servlet:
package com.guigu.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class checkUserName extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); List<String> userStrings = new ArrayList<String>(); userStrings.add("aa"); userStrings.add("bb"); Object userName = request.getParameter("userName"); Boolean flageBoolean = userStrings.contains(userName); if (flageBoolean) { response.getWriter().print("<font color=‘red‘>该名字已经注册</font>"); }else { response.getWriter().print("<font color=‘red‘>没注册</font>"); } } }
总结:
(1)返回的数据类型包括html(可以直接插入文档,也可以选择器过滤,但是有局限性)、xml(万能的数据传输,比较笨重)、json(最常用,轻巧方便)
(2)当用$.get()时,需要告诉返回数据的类型,否则无法解析数据
(3)当返回数据是xml,json时,都是先解析数据,构建html节点,最后加入文档。
以上是关于ajax的主要内容,如果未能解决你的问题,请参考以下文章