前端之家收集整理的这篇文章主要介绍了
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>
<script type="text/javascript" src="js/test.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form >
用户名:<input type="text" id="name" /><br/>
<input type="submit" id="OK" value="校验" />
</form>
</body>
</html>
function ajaxFunction()
{
var xmlHttp=null;
try
{
// Firefox,Opera 8.0+,Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}
window.onload=function()
{
document.getElementById("OK").onclick=function()
{
//alert("wuuuu");
/*
* 1.获取xmlHttpRequest
* */
var xmlReq=ajaxFunction();
/*
* 4.接手服务器的响应
*
* */
//alert("wuuuu");
xmlReq.onreadystatechange=function()
{
if(xmlReq.readyState==4)
{
alert(xmlReq.readyState);
alert(xmlReq.status);
if(xmlReq.status==200||xmlReq.status==304)
{
alert("wu");
var data=xmlReq.responseText;
alert(data);
}
}
}
/*
* 2.打开服务器的连接,* 第三个参数为true(异步的)
* 第一个参数:传递方法
* 第二个方法是路径
* */
//alert("路径整的不对啊???怎么改过来???");
xmlReq.open("get","/Ajax/Demo1",true);
alert("adsada");
/*
* 3.发送数据
* */
xmlReq.send(null);
}
}
package cn.com.Demo;
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;
import javax.servlet.jsp.PageContext;
public class Demo1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
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();
//out.write("OK");
System.out.println("--------------------------------------");
}
public void doPost(HttpServletRequest request,IOException {
doGet(request,response);
}
}
原文链接:https://www.f2er.com/ajax/165753.html