AJAX全称是异步JS和XML(数据传输格式)
AJAX是一种局部刷新的技术, 相较于全局刷新, AJAX的用户体验更好
异步对象(核心):XMLHttpRequest对象
var xmlHttp = new XMLHttpRequest();
readyState:请求的状态变化
0: 请求未初始化, 创建异步请求对象 var xmlHttp = new XMLHttpRequest();
1: 初始化异步请求对象, xmlHttp.open(请求方式get|post,服务器访问地址,同步|异步(true|false))
2: 异步对象发送请求, xmlHttp.send()
3: 异步对象接收服务端返回的数据, XMLHttpRequest 异步对象内部处理
4: 异步请求对象已经将数据解析完毕, 开发人员可以处理数据, 更新当前页面展示数据
status:网络请求状况状态码
200:正常
404:路径不对
500:代码不对
responseText:获取从服务端返回的数据
var data = xmlHttp.responseText
onreadystatechange: 异步对象发起情况和获得数据都会触发该事件
xmlHttp.onreadystatechange = function(){
处理请求的状态变化
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//请求为4并且网络为200时可以正常运行,处理服务端返回数据,更新当前页面
}
}
xmlHttp.open(请求方式get|post,服务器访问地址,同步|异步(true|false));
例如:
xmlHttp.open("get", "loginServlet?name=zs&pwd=123", "true");
xmlHttp.send()
回调函数:当请求的状态发生变化时,异步对象会自动调用onreadystatechange事件对应的函数
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.klrss.controller.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/ajaxServlet</url-pattern><!--跳转地址-->
</servlet-mapping>
方式一:request跳转,前台EL表达式展示数据
request.setAttribute("msg", msg);
request.getRequestDispatcher("跳转的地址").forward(request,response);
方式二:responseIO流跳转,前台EL表达式展示数据
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.println(msg);
pw.flush();
pw.close();
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>局部刷新Ajax</title>
</head>
<body>
<div>
姓名:<input type="text" id="name"><br>
体重(公斤):<input type="text" id="weight"><br>
升高(米):<input type="text" id="height"><br>
<input type="submit" value="提交" onclick="doAjax()">
<br>
<div id="myData">
等待加载数据
</div>
</div>
<script type="text/javascript">
function doAjax() {
//创建异步对象
var xmlHttp = new XMLHttpRequest(); //0
//绑定事件,回调函数:请求的状态发生变化都会调用该函数
xmlHttp.onreadystatechange = function () {
//处理数据,返回结果
//alert("状态码"+xmlHttp.readyState+"网络码"+xmlHttp.status)
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// alert(xmlHttp.responseText);
var data = xmlHttp.responseText;
document.getElementById("myData").innerText = data;
}
}
//初始请求数据
var name = document.getElementById("name").value;
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var param = "name=" + name + "&weight=" + weight + "&height=" + height;
alert(param);
xmlHttp.open("get", "ajaxServletTest?" + param, true);//1
//发送数据
xmlHttp.send();//2
}
</script>
</body>
</html>
package com.klrss.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AjaxServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得前台数据
String name = req.getParameter("name");
String height = req.getParameter("height");
String weight = req.getParameter("weight");
Float h = Float.valueOf(height);
Float w = Float.valueOf(weight);
//bmi
float bmi = w / (h * h);
String msg = "";
if (bmi <= 18.5) {
msg = "瘦";
} else if (bmi > 18.5 && bmi < 23.9) {
msg = "正常";
} else if (bmi > 23.9 && bmi < 27) {
msg = "胖";
} else {
msg = "肥胖";
}
System.out.println("msg=" + msg);
msg = "你好" + name + "先生/女生" + bmi + "," + msg;
//IO流
resp.setContentType("text/html;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.println(msg);
pw.flush();
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//get请求
xmlhttp.open("GET","ajaxServlet?username=tom",true);//post请求
xmlHttp.open("post","ajaxServlet",true);//get发送请求
xmlhttp.send();//post发送请求
xmlHttp.send("id="+inputVal);
含义:json是一串由键值对组成的字符串,代表一个对象或者一组对象
作用:以对象的形式交换前台和后台的数据, 更加轻量级(代替xml),传输速度快,用户体验好
var person = {"name":"张三","age":19,"gender":"男"};
var persons = [
{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}
];
Gson(谷歌)
FastJson(阿里巴巴)
Jackson
Json-lib
//创建jackson的对象
ObjectMapper om = new ObjectMapper();
//使用jackson对象的转换方法将封装数据转化为字符串
String json = om.writeValueAsString(province);
System.out.println(json);
//使用eavl函数,注意
var data = xmlHttp.responseText;
var jsonObj = eval("("+data+")");
加括号的问题?
因为data是{}环绕的(data = {...}),在js中被当作语句块处理, 通过加()强制把它转成表达式, 才能转换为JSON对象
alert(eval("{}"));
alert(eval("({})"));
Ctrl+Shift+Alt+s 快速打开模块设置
//省份不等于空且省份(删除首位空白符)不等于空proid != null && !"".equals(proid.trim())//另一种方法proid.trim().length() > 0
原文:https://www.cnblogs.com/klrss/p/15269282.html