ajax入门案例以及乱码问题

前端之家收集整理的这篇文章主要介绍了ajax入门案例以及乱码问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。这就是AJAX的优势了,可以使网页从服务器请求少量的信息,而不是整个页面
下面通过一个简单的小案例帮助大家进一步理解AJAX,先看效果图:
1: 前台是一个简单的获取当前页面的值和AJAX,已给出相应的注释,不懂留言:
<%@ 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>My JSP 'Login.jsp' starting page</title>
    
	<Meta http-equiv="pragma" content="no-cache">
	<Meta http-equiv="cache-control" content="no-cache">
	<Meta http-equiv="expires" content="0">    
	<Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<Meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		
		function btn_click(){
			//创建XMLHttpRequest对象
			var xmlHttp;
			xmlHttp=new XMLHttpRequest();
			try{
				//兼容Firefox,Opera8.0+,Safari
				xmlHttp=new  XMLHttpRequest();
			}catch(e){
				//兼容IE
				try{
					xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				}catch(e){
					try{
						xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
					}catch(e){
						alert("您的浏览器不支持ajax");
						return false;
					}
				}
			}
			//获取文本框的值
			var username=document.getElementById("txt_username").value;
			var password=document.getElementById("txt_password").value;
			//设置编码,避免中文出现乱码。
			username=encodeURIComponent(encodeURIComponent(username));
			//配置XMLHttpRequest对象
			xmlHttp.open("GET","servlet/LoginServlet?username="+username+"&password="+password,true);
			//设置回调函数
			xmlHttp.onreadystatechange=function(){
				if(xmlHttp.readyState==0){
					docuement.getElementById("result").innerHTML="未初始化.还没调用open()..";
				}else if(xmlHttp.readyState==1){
					docuement.getElementById("result").innerHTML="正在连接服务器.还没调用send()..";
				}else if(xmlHttp.readyState==2){
					docuement.getElementById("result").innerHTML="正在加载信息...";
				}else if(xmlHttp.readyState==3){
					docuement.getElementById("result").innerHTML="正在连收数据...";
				}else if(xmlHttp.readyState==4){//表示交互完毕
					if(xmlHttp.status==200){//200对应ok ,
						document.getElementById("result").innerHTML=xmlHttp.responseText;
					}else{
						docuement.getElementById("result").innerHTML="出错了";
					}
				}else{
					docuement.getElementById("result").innerHTML="网络异常...";
				}
				
			}
			
			xmlHttp.send(null);
		}
	</script>
  </head>
  
  <body>
    <label>姓名:</label><input type="text" id="txt_username"/><br/>
    <label>密码:</label><input type="password" id="txt_password"/><br/>
    <input type="button" value="获取文本框的值" id="btn" onclick="btn_click()"/><br/>
   
    <div id="result"></div>
  </body>
</html>

2. 后台是一个servlet 主要是接收前台传过来的值并且为前台提供必要的值,代码如下:
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		
		PrintWriter out = response.getWriter();
		String username=request.getParameter("username");
		//设置编码,避免出现乱码
		username = URLDecoder.decode(username,"utf-8");
		String password=request.getParameter("password");
		System.out.println("username----"+username+"<br>password----"+password+"<br>date----"+new Date());
		out.println("username----"+username+"<br>password----"+password+"<br>date----"+new Date());
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request,IOException {

	
		
	}

}

3.配置文件web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/servlet/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

这是本人学AJAX写的第一个例子,写的不足之处望见谅,指出缺点,不胜感激。

猜你在找的Ajax相关文章