基于JSON的数据交换:就是说对于服务器将往前端发送的数据包装成JSON类型,那么前端该如何从JSON类型的数据中调取自己需要的信息呢?这就是需要关注的两点
服务器将返回的数据包装成json类型的数据:
第一种方式后端代码编写:【由于发文限制,所以将所有的密码改为pd】
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置响应格式
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
StringBuilder json = new StringBuilder();
String jsonstr = "";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
// String str = "{\"username\":\"zhngsan\", \"pd\":\"123456\"}";
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
json.append("[");
while (rs.next()){
String username = rs.getString("username");
String pd = rs.getString("pd");
//{"username":" zhangsan ", "pd":" 123456 "},
json.append("{\"username\":\"");
json.append(username);
json.append("\", \"pd\":\"");
json.append(pd);
json.append("\"},");
}
jsonstr = json.substring(0,json.length()-1)+"]";
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
out.print(jsonstr);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Student> studentList = new ArrayList<>();
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String username = rs.getString("username");
String password = rs.getString("password");
Student student = new Student(username,password);
studentList.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
String jsonString = JSON.toJSONString(studentList);
out.print(jsonString);
}
window.onload = function () {
document.getElementById("btn").onclick = function (){
//1.创建核心对象
var xhr = new XMLHttpRequest();
//2.获取服务器数据
xhr.onreadystatechange = function () {
var html = ""
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var json = JSON.parse(this.responseText);
for (var i = 0; i < json.length; i++){
var stuJson = json[i];
html += ""
html +=stuJson.username
html +=" "
html +=stuJson.password
html +=" "
}
document.getElementById("tbody").innerHTML = html
}else{
alert(this.status)
}
}
}
//3.打开通道
// xhr.open("GET","/ajax/request5",true);
xhr.open("GET","/ajax/request6",true);
//4.发送数据
xhr.send();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置响应的数据类型为xml
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
StringBuilder xml = new StringBuilder();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
xml.append("" );
while (rs.next()) {
String username = rs.getString("username");
String password = rs.getString("password");
xml.append("" );
xml.append("" );
xml.append(username);
xml.append("");
xml.append("" );
xml.append(password);
xml.append("");
xml.append("");
}
xml.append("");
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
out.print(xml);
}
前端对接受到的数据解封装:
window.onload = function () {
document.getElementById("btn").onclick = function (){
//1.创建JSON核心对象
var xhr = new XMLHttpRequest();
//2.
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
//
var xmlDoc = this.responseXML;
// console.log(xmlDoc)
var html = "";
var students = xmlDoc.getElementsByTagName("student");
//遍历所有的student
for (var i = 0; i < students.length; i++){
//获取单个student
var student = students[i]
//获取student下的所有子节点
html += ""
var childNodes = student.childNodes;
for (var j = 0; j < childNodes.length; j++){
var node = childNodes[j];
if (node.nodeName == "username"){
// console.log("name="+node.textContent)
html += ""+node.textContent+" "
}else {
html += ""+node.textContent+" "
}
}
html += " "
}
document.getElementById("tbody").innerHTML = html
}else{
alert(this.status)
}
}
}
//3.打开通道
xhr.open("GET","/ajax/ajaxrequest7",true)
//4.发送数据
xhr.send();
}
}
通过对一下问题的测试得出结论:tomcat10版本解决了乱码问题,后端程序不需要理会这个问题,Tomcat10之前的版本还没有解决,需要程序员设置编码方式
发送ajax get请求
发送ajax post请求
对于Tomcfat9以及之前版本响应中文的时候,出现乱码解决?
response.setContentType("text/html;charset=UTF-8");
发送ajax post请求的时候,发送给服务器的数据,服务器接收之后乱码,怎么解决?
request.setCharacterEncoding("UTF-8");