Ajax结合Json进行交互数据(四)
<%@ 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">
//json对象
function loadInfo(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataObj=eval("("+xmlHttp.responseText+")");//得到的是json对象
alert(dataObj.name);//因为是json对象,所以能点属性
alert(dataObj.age);
document.getElementById("name").value=dataObj.name;
document.getElementById("age").value=dataObj.age;
}
};
xmlHttp.open("get", "getAjaxInfo?action=jsonObject", true);
xmlHttp.send();
}
//json数组
function loadInfo2(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataObj=eval("("+xmlHttp.responseText+")");
var st=document.getElementById("studentTable");
alert(dataObj.students.length);
var newTr; // 行
var newTd0; // 第一列
var newTd1; // 第二列
var newTd2; // 第三列
for(var i=0;i<dataObj.students.length;i++){
var student=dataObj.students[i];
newTr=st.insertRow();
newTd0=newTr.insertCell();
newTd1=newTr.insertCell();
newTd2=newTr.insertCell();
newTd0.innerHTML=student.name;
newTd1.innerHTML=student.age;
newTd2.innerHTML="语文:"+student.score.chinese+",数学:"+student.score.math+",英语:"+student.score.english;
}
}
};
// xmlHttp.open("get", "getAjaxInfo?action=jsonArray", true);
xmlHttp.open("get", "getAjaxInfo?action=jsonNested", true);
xmlHttp.send();
}
</script>
</head>
<body>
<div style="text-align: center;">
<div><input type="button" onclick="loadInfo()" value="Ajax获取信息"/> 姓名:<input type="text" id="name" name="name" /> 年龄:<input type="text" id="age" name="age" /></div>
<div style="margin-top: 20px;">
<input type="button" onclick="loadInfo2()" value="Ajax获取信息2"><br/>
<table id="studentTable" align="center" border="1px;" cellpadding="0px;">
<tr>
<th>姓名</th><th>年龄</th><th>得分</th>
</tr>
</table>
</div>
</div>
</body>
</html>
package com.wp.servlet 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 net.sf.json.JSONArray;
import net.sf.json.JSONObject; public class GetAjaxInfoServlet 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,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String action = request.getParameter("action");
if ("jsonObject".equals(action)) {
this.getJsonObject(request, response);
} else if ("jsonArray".equals(action)) {
this.getJsonArray(request, response);
} else if ("jsonNested".equals(action)) {
this.getJsonNested(request, response);
} } /**
* json对象
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void getJsonObject(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
// String resultJson="{\"name\":\"张三\",\"age\":22}";//斜杠在这里是转义
JSONObject resultJson = new JSONObject();
resultJson.put("name", "张三");
resultJson.put("age", 22);
out.println(resultJson);
out.flush();
out.close();
} /**
* 简单的json数组
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void getJsonArray(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
JSONObject resultJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24);
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3); resultJson.put("students", jsonArray);
out.println(resultJson);
out.flush();
out.close();
} /**
* 多重json嵌套
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void getJsonNested(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); JSONObject resultJson = new JSONObject();// 创建最后结果的json JSONArray jsonArray = new JSONArray();// json数组
JSONObject jsonObject1 = new JSONObject();// json对象
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22); JSONObject scoreObject1 = new JSONObject();
scoreObject1.put("chinese", 90);
scoreObject1.put("math", 100);
scoreObject1.put("english", 80);
jsonObject1.put("score", scoreObject1); JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23); JSONObject scoreObject2 = new JSONObject();
scoreObject2.put("chinese", 70);
scoreObject2.put("math", 90);
scoreObject2.put("english", 90);
jsonObject2.put("score", scoreObject2); JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24); JSONObject scoreObject3 = new JSONObject();
scoreObject3.put("chinese", 80);
scoreObject3.put("math", 60);
scoreObject3.put("english", 90);
jsonObject3.put("score", scoreObject3);
// {"score":{"chinese":80,"math":60,"english":90}}
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);
// {"name":"王五","age":24,"score":{"chinese":80,"math":60,"english":90}}
resultJson.put("students", jsonArray);// "students":[数组]
// {"student":[{"name":"王五","age":24,"score":{"chinese":80,"math":60,"english":90}}]}
out.println(resultJson);
out.flush();
out.close();
}
}
ajax通过XMLHttpRequest的open和send方法进行请求,servlet端就是一个服务器端在接收请求后,通过response.getWriter()得到输出字符流,然后在html页面上通过XMLHttpRequest的responseText来得到响应的信息。
Java小生店铺:
Pc端:http://shop125970977.taobao.com/index.htm
手机端:搜索 java小生店铺
希望店铺的资料能帮助到你!!!

Ajax结合Json进行交互数据(四)的更多相关文章
- Ajax获取 Json文件提取数据
摘自 Ajax获取 Json文件提取数据 1. json文件内容(item.json) [ { "name":"张国立", "sex":&q ...
- Ajax--PHP+JQuery+Ajax解析json、XML数据、加载页面
一.JQuery+Ajax用get.post方式提交和请求数据 知识要点: $('#userName').blur(function () { var txt = $(this).val(); $.a ...
- 通过Ajax post Json类型的数据到Controller
View function postSimpleData() { $.ajax({ type: "POST", url: "/Service/SimpleData&quo ...
- jquery ajax提交json格式的数据,后台接收并显示各个属性
我的表单如下: <form onsubmit="return false"> <ul> <li><span>用户名</span ...
- ajax请求json中的数据
在这里不多说,直接可以运行代码看效果: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta ...
- 如何使用ajax将json传入后台数据
首先采用jquery内部封装好的方法是比较简单的,我们只需做的就是修改里面的一些配置: 对$.ajax()的解析: $.ajax({ type: "POST", //提交方式 co ...
- AJAX获取JSON形式的数据
test.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...
- 把数据转化为JSON格式用ajax进行前后端交互
接着在https://www.cnblogs.com/dong973711/p/10907733.html的基础上做验证. 从前端提交数据 前端页面,submit.html <!DOCTYPE ...
- Django--多对多表的创建、contentType、ajax、ajax传输json数据格式、ajax传输文件数据、 自定义分页器
MTV与MVC(了解): MTV模型(Django用的就是MTV): M:模型层(models.py) T:templates C:views MVC模型: M:模型层(models.py) V:视图 ...
随机推荐
- 11.ingress服务
kubernetes 的service服务我们提到过.service 可以用nodePort的方式和调用公有云LBAAS服务 来对于集群外的client提供服务访问,但是service是工作的osi ...
- matlab——sparse函数和full函数
转载:http://www.cnblogs.com/lihuidashen/p/3435883.html matlab——sparse函数和full函数(稀疏矩阵和非稀疏矩阵转换) 函数功能:生成 ...
- Nginx 简单的cpu配置
配置指定CPU Nginx建议进程数和CPU数量一致,这样每个CPU都有自己独立的缓存 worker_processes 4; worker_cpu_affinity 1000 0100 0010 0 ...
- 下载模板、Excel导入、导出
下载模板 /// <summary> /// 下载模板 /// </summary> /// <returns></returns> public Ac ...
- python数学库math模块
函数 数学表示 含义 .pi 圆周率π π的近似值,15位小数 .e 自然常数 e e的近似值,15位小数 ceil(x) [x] 对浮点数向上取整 floor(x) [x] 对浮点数向下取整 pow ...
- Codeforces Round #426 Div. 1
A:考虑每个质因子,显然要求次数之和是3的倍数,且次数之差的两倍不小于较小的次数.对于第一个要求,乘起来看开三次方是否是整数即可.第二个取gcd,两个数分别除掉gcd,之后看两个数的剩余部分是否都能被 ...
- Django ContentType组件
ContentType组件 引入 现在我们有这样一个需求~我们的商城里有很多的商品~~节日要来了~我们要搞活动~~ 那么我们就要设计优惠券~~优惠券都有什么类型呢~~满减的~折扣的~立减的~~ 我们对 ...
- Girls and Boys HDU - 1068 二分图匹配(匈牙利)+最大独立集证明
最大独立集证明参考:https://blog.csdn.net/qq_34564984/article/details/52778763 最大独立集证明: 上图,我们用两个红色的点覆盖了所有边.我们证 ...
- HDU1800 字典树写法
题意:高级魔法师可以教低级魔法师 魔法扫把技能,同时教会了的低级魔法师又可以教比他更低级是,是传递的关系 同时如果教会了的话,他们可以同时坐一个扫把 问最少需要多少个扫把 思路:就是判断相同的数字最多 ...
- 【vijos1780】【NOIP2012】开车旅行 倍增
题目描述 有\(n\)个城市,第\(i\)个城市的海拔为\(h_i\)且这\(n\)个城市的海拔互不相同.编号比较大的城市在东边.两个城市\(i,j\)之间的距离为\(|h_i-h_j|\) 小A和小 ...