前端之家收集整理的这篇文章主要介绍了
2. Ajax 核心知识,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
document.getElementById("name").value=xmlHttp.responseText;
}
};
// xmlHttp.open("get","getAjaxName?name=jack&age=11",true);
// xmlHttp.open("post",true);
// xmlHttp.send();
xmlHttp.open("post","getAjaxName",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("name=jack&age=11");
}
</script>
</head>
<body>
<div style="text-align: center;">
<div><input type="button" onclick="loadName()" value="Ajax获取数据"/> <input type="text" id="name" name="name" /></div>
</div>
</body>
</html>
package com.java1234.web;
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 GetAjaxNameServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request,IOException {
String name=request.getParameter("name");
String age=request.getParameter("age");
System.out.println("name="+name);
System.out.println("age="+age);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("ajax返回的文本");
out.flush();
out.close();
}
}
原文链接:https://www.f2er.com/ajax/162067.html