ajax的两种提交方式(get/post)和两种版本
2024-09-01 08:28:58
供稿:网友
 
最近比较闲,就把以前用过的技术串一下做个手札,方便以后自己偷懒,小鸟你们幸福了。 
首先主要是将javascript版本ajax做下注释:ajax异步刷新主要是将所需条件拼成字符串传入后台,处理之后,直接调用回调函数将所得数据返还给页面,并加以显示,因为还在本页面,所以不用刷新页面,懂了了吧,本篇也用encodeURI对字符串做了加密,并在类里做了解码,其中需要一些注意的地方在源码里做了注释。get/post两种提交方式,但get提交容易乱码,一定多加注意 
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%>"> 
<script type="text/javascript" > 
var xmlHttp; 
function createxmlHttpRequest(){ 
if(window.XMLHttpRequest){ 
xmlHttp= new XMLHttpRequest();//IE7+,FireFox,Opera,Safari,Chrome 
}else{ 
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
} 
function test(){//get 
//获取参数 
//var unames=encodeURI(document.getElementById("username").value);//一次编码java用new String(name.getBytes("ISO8859-1"), "UTF-8")解码 
var unames=encodeURI(encodeURI(document.getElementById("username").value));//两次编码才能用java.net.URLDecoder.decode(name,"utf-8");解码 
var pws=encodeURI(document.getElementById("password").value); 
createxmlHttpRequest(); 
xmlHttp.onreadystatechange=readyState; 
//function(){ 
//alert(xmlHttp.readyState+"=="+xmlHttp.status);//判断请求状态 
//} 
xmlHttp.open("get","AjaxServlet1?msg=gets&name="+unames+"&pwd="+pws+"&timeStamp="+new Date().getTime(),true); //get 方式提交中文会出现乱码,encodeURI()/encodeURIComponent()将中文转成16进制编码,把字符串作为URI进行编码 
xmlHttp.send(null); 
} 
function testp(){//post 
//获取参数 
var unames=document.getElementById("username").value; 
var pws=document.getElementById("password").value; 
createxmlHttpRequest(); 
xmlHttp.onreadystatechange=readyState; 
xmlHttp.open("post","AjaxServlet1",true); 
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
var str="msg=posts&name="+unames+"&pwd="+pws+"&timeStamp="+new Date().getTime(); 
xmlHttp.send(str);//send 可用于传参 
} 
function readyState(){ 
if(xmlHttp.readyState==4){ 
if(xmlHttp.status==200){ 
var msg= xmlHttp.responseText; 
//alert(msg); 
document.getElementById("result").innerHTML=msg; 
} 
} 
} 
</script> 
<title>js异步刷新</title> 
</head> 
<body> 
<center> 
<div id="response"> 
</div>