ajax.js文件
var xmlhttp=null;
//创建XMLHttpRequest对象
function createHttpRequest(){
if(window.XMLHttpRequest){ //Mozilla 浏览器
xmlhttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //新版IE
}catch(e){
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlhttp = null;
}
}
}
if(!xmlhttp){ //创建XMLHttpRequest失败
alert("不能创建XMLHttpRequest对象实例");
}
}
//发送函数
function sendRequest(method,url,param,callbackHandler){
//创建对象
createHttpRequest();
//绑定事件,后台返回的数据,通过callback方法处理
xmlhttp.onreadystatechange = callbackHandler;
if(method=="get" || method=="GET"){
//初始化发送信息
xmlhttp.open(method,url + "?" + param,true);
xmlhttp.send(null);
}
if(method=="post" || method=="POST"){
//初始化发送信息
xmlhttp.open(method,url,true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(param);
}
}
封装案例前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax应用</title>
</head>
<script src="../js/ajax.js"></script>
<script type="text/javascript">
//接受返回结果
function callback(){
if(xmlhttp.readyState == 4){ //发送完成
if(xmlhttp.status == 200) { //响应成功
//业务处理代码
alert(xmlhttp.responseText);
/*
* 返回结果:
* 获取返回普通文本内容:responseText
* 获取返回xml格式的数据:responseXml
*
*
* */
}else{
//报错
alert(xmlhttp.status);
}
}
}
function sendData(){
var num = document.getElementById("num").value;
var url = "http://localhost:8080/ajaxProj/ajaxServlet";
var param = "num=" + num;
sendRequest("get",url,param,callback);
}
</script>
<body>
<h2 align="center">ajax应用</h2>
<hr>
<input type="text" name="num" id="num" value="10">
<input type="button" value="发送请求到ajaxServlet" onclick="sendData()">
</body>
</html>
封装案例后端
package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "AjaxServlet",value = "/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String num = request.getParameter("num");
System.out.println("num=" + num);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("接收成功num的值:" + num);
out.close();
}
}
本人从事软件项目开发20多年,2005年开始从事Java工程师系列课程的教学工作,录制50多门精品视频课程,包含java基础,jspweb开发,SSH,SSM,SpringBoot,SpringCloud,人工智能,在线支付等众多商业项目,每门课程都包含有项目实战,上课PPT,及完整的源代码下载,有兴趣的朋友可以看看我的在线课堂
讲师课堂链接:https://edu.csdn.net/lecturer/893