日期:2014-05-16  浏览次数:20665 次

Ajax 与 服务器的集中传递数据以及解析的格式
传递数据的方式
1.普通的文本的方式
2.XML方式
3.JSon方式

特别要注意的是xml传递方式和Json传递方式的各自的优缺点,可以说是各有用武之地。本人刚学不久,废话不说了,直接代码贴上了。哈哈,有兴趣的朋友可以下载下去看看。

1.普通的文本的方式

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>My JSP 'index.jsp' starting page</title>

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="js/ajax.js">
</script>
  </head>
 
  <body>
  <div>
  用户名:<input type="text" id="name" size="15"/><br/>
  密&nbsp; &nbsp;&nbsp;码:<input type="password" id="password" size="16"/><br/>
<input type="button" value="登录" onclick="return verifyUser()"/><br/>
<span id="result"></span>
</div>
  </body>
</html>


ajax.js

//XMLHttpRequest Object
var xhr ;

//create XMLHttpRequest Object
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("你的浏览器不支持Ajax");
}
}

}
}

//发送请求
function sendRequest(name,password){
//返回的结果
var result;
createXMLHttpRequest();
xhr.open("GET","LoginServlet?name="+name+"&password="+password,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
result = xhr.responseText;
//alert(result);
//write the result to web page
var spanResult = document.getElementById("result");
spanResult.innerHTML = result;
}else{
alert("error");
}
}
}
xhr.send(null);
}

function verifyUser(){
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;

if(name.trim() == '' || password.trim()==''){
alert("用户名或者密码为空")
return false;
}

//发送用户名和密码到服务器进行校验
sendRequest(name,password);

}

//为String添加trim 方法
String.prototype.trim = function () {
    return   this .replace(/^\s+|\s+$/g, '' );
}


LoginServlet.java

package com.action;

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 LoginServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String result = "";
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String password = request.getParameter("password");
if("admin".equals(name) && "admin".equals(password)){
result = "登录成功";
}else{
result = "用户名或者密码错误";
}

response.setContentType("text/html;charset=U