首页 > Web开发 > 详细

11.Ajax JSON

时间:2018-02-22 22:54:02      阅读:201      评论:0      收藏:0      [点我收藏+]

概述:

**ajax技术的开发步骤及其入门(开发的步骤比较固定)**
	
	1.学习ajax掌握XMLHttpRequest对象。
		* 使用异步的技术,需要使用XMLHttpRequest对象。
		* 该对象封装HTTP的协议
			* 也可以采用GET或者POST方式请求服务器
			* 获取服务器端的响应的内容
				* 响应都是字符串或者XML文档
	
	2.ajax技术开发,编写代码的步骤就是固定的。
	3.开发的入门步骤(固定的)
		var xhr = new XMLHttpRequest();	-- 支持火狐、谷歌或者IE的高版本的浏览器		
		* 第一步:需要先获取到XMLHttpRequest对象。
			
			function createXMLHttpRequest(){
				try {
					// 如果是你是IE高版本  火狐 谷歌 
					return new XMLHttpRequest();
				} catch (e) {
					try {
						// 如果是IE6的版本
						return new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e) {
						try {
							// 如果是IE5.5版本
							return new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e) {
							alert("大哥!您这是什么浏览器呀!!");
						}
					}
				}
			}
		
		* 第二步
			* 如果第一步已经获取到了XMLHttpRequest对象了,下一步,需要连接访问服务器端资源。
			* open("请求方式","请求资源的路径",boolean);
				* 3个方法的含义
					* 1.代表的请求的方式,常用的有GET或者POST
					* 2.代表的请求资源的路径,例如:${pageContext.request.contextPath}/xxxservlet
					* 3.值是boolean类型的值,如果是true,说明的异步操作,如果是false,说明是同步操作。一般情况下是true
		
		* 第三步
			* 发送请求的参数
			* send(请求体的内容);
			* 如果请求方式是POST请求,send方法中正常传递参数了。xhr.send("username="+haha+"&password="+123)
			* 如果请求方式是GET请求,send方法一般就不传递参数了。
				* 可以使用open方法来传递参数:例如:${pageContext.request.contextPath}/xxxservlet?username=haha
				* 如果GET请求,一般还不传递参数的情况下,send一般传递null	xhr.send(null);
		
		* 第四步
			* 整体的目的:接收服务器端做出的响应。但是要怎么来接收呢?
			* XMLHttpRequest提供了属性,使用该属性监听XMLHttpRequest对象的状态的改变。该XMLHttpRequest对象由哪些状态
				* 0		-- 刚创建该对象
				* 1		-- 调用open方法,还没有发生请求
				* 2		-- 已经调用了send方法,发送了请求,但是还没有得到响应
				* 3		-- 做出了响应,但是有可能响应没有结束
				* 4		-- 响应结束了
			
			* 代码如下
				xhr.onreadystatechange = function(){
					// 做出判断,如果xhr的对象状态已经为4了,说明响应已经结束了
					// 不仅会判断状态是否为4,还会判断状态码是否为200
					if(xhr.readyState == 4 && xhr.status == 200){
						// 在该位置,获取到响应的内容了。
						
						// 接收响应的代码
						var result = xhr.responseText;
					}
				};
		
		* 第五步
			* 接收响应的内容
				* 如果服务器端响应的是字符串,var result = xhr.responseText;	result就代表的是字符串
				* 如果服务器端响应的XML的内容,var result = xhr.responseXML;	result就代表的是document对象(现在不用了)

 

**入门的案例**

  1.需求:在JSP的页面上,提供一个按钮,点击按钮,偷偷的发送异步请求(页面没提交),让按钮下方的<h4>标题中显示内容(服务器端响应的内容)
  2.编写代码
    * 客户端
    * 采用的异步的方式
    * 采用XMLHttpRequest对象

    * 服务器端
    * 在控制台输出一句话
    * 响应的字符串的内容

<%@ 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">
	/**
	*	1.创建XMLHttpRequest对象
		2.调用open() 连接资源
			*提交方式
			*连接资源路径
			*boolean true代表异步
		3.调用send() 发送请求
		4.监听对象的状态的改变,要4状态,代表响应结果
		5.获取到服务器响应的内容
	*/
	
	//点击按钮,发送异步请求
	function run(){
		//1.创建XMLHttpRequest对象    var xhr=new XMLHttpRequest();
		var xhr=createXMLHttpRequest();
		
		//2.调用open() 连接资源
		xhr.open("GET","${pageContext.request.contextPath}/ajax1",true);
		
		//3.调用send() 发送请求    get方式,里面传null
		xhr.send(null);
		
		//4.监听对象的状态的改变,要4状态,代表响应结果(状态一改变,就会执行)
		xhr.onreadystatechange=function(){
			//判断,对象的状态是否是4状态,如果是说明响应结束了
			if(xhr.readyState==4 && xhr.status==200){
				//5.获取到服务器响应的内容
				var result=xhr.responseText;
				//显示到h4标签的中间
				document.getElementById("h4Id").innerHTML=result;
			}
		}
	}
	
	
	//兼容大多数浏览器,获取XMLHttpRequest对象
	function createXMLHttpRequest(){
		try{
			//如果你是IE高版本 火狐 谷歌
			return new XMLHttpRequest();
		}catch(e){
			try{
				//如果是IE6的版本
				return new ActiveXObject("Msxml2.XMLHTTP");
				
			}catch(e){
				try{
					//如果是IE5.5版本
					return new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){
					alert("亲,你这是什么浏览器啊!");
				}
			}
		}
	} 
	
</script>

</head>
<body>

<h3>ajax的入门</h3>

<input type="button" value="点我" onclick="run()"/>

<h4 id="h4Id"></h4>

</body>
</html>

Ajax1Servlet:

public class Ajax1Servlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("请求成功了");
		//做出响应
		response.getWriter().print("hello ajax!!");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}
}

  

**ajax发送POST请求**

  1.向服务器发送的POST请求
    * xhr.open("POST","地址",true)
    * 设置请求的头的信息
    * xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    * xhr.send(参数);

  2.编写代码演示POST请求

<%@ 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">
	/**
	*	1.创建XMLHttpRequest对象
		2.调用open() 连接资源
			*提交方式
			*连接资源路径
			*boolean true代表异步
		3.调用send() 发送请求
		4.监听对象的状态的改变,要4状态,代表响应结果
		5.获取到服务器响应的内容
	*/
	
	//点击按钮,发送异步请求
	function run(){
		//1.创建XMLHttpRequest对象    var xhr=new XMLHttpRequest();
		var xhr=createXMLHttpRequest();
		
		//2.调用open() 连接资源
		xhr.open("POST","${pageContext.request.contextPath}/ajax2",true);
		
		//发送请求参数之前,手动设置头
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		//发送请求参数
		xhr.send("username=zhangsan");
		
		//监听对象状态的改变
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4 && xhr.status==200){
				var result=xhr.responseText;
				document.getElementById("h4Id").innerHTML=result;
			}
		}
	}
	
	//兼容大多数浏览器,获取XMLHttpRequest对象
	function createXMLHttpRequest(){
		try{
			//如果你是IE高版本 火狐 谷歌
			return new XMLHttpRequest();
		}catch(e){
			try{
				//如果是IE6的版本
				return new ActiveXObject("Msxml2.XMLHTTP");
				
			}catch(e){
				try{
					//如果是IE5.5版本
					return new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){
					alert("亲,你这是什么浏览器啊!");
				}
			}
		}
	} 
	
</script>

</head>
<body>

<h3>ajax的入门(发送的是POST请求)</h3>

<input type="button" value="点我" onclick="run()"/>

<h4 id="h4Id"></h4>

</body>
</html>

Ajax2Servlet:

public class Ajax2Servlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("请求成功");
		String username=request.getParameter("username");
		System.out.println("名称:"+username);
		response.getWriter().print(username);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

  

**ajax完成用户名是否已经存在**

  1.需求:验证用户名是否已经存在?
  2.准备环境
    * 客户端
    * 注册的jsp的页面

    * 服务器端
    * 后台的程序,通过传过来的用户名去数据库查询
    * 如果数据库中已经存在该用户名,说明不能注册的!
    * 如果不存在该用户名,可以注册!

regist.jsp:

<%@ 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>
</head>
<script type="text/javascript">
 	function run(){
 		var xhr=createXMLHttpRequest();
 	
 		xhr.open("POST","${pageContext.request.contextPath}/user",true);
 		
 		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 	
 		var username=document.getElementById("nameId").value;
 		
 		/*  innerHTML只取一些文本标签里有内容,比如 div  span  p  等这里不能输入的标签里有内容。
 		value是取一取输入框的值  比喻 input textarea  select 等等。   */
 	
 		xhr.send("username="+username);
 		
 		xhr.onreadystatechange=function(){
 			if(xhr.readyState==4 && xhr.status==200){
 				var result=xhr.responseText;
 				document.getElementById("uSpan").innerHTML=result;
 			}
 		}
 		
 	}
 	
 	function createXMLHttpRequest(){
		try{
			//如果你是IE高版本 火狐 谷歌
			return new XMLHttpRequest();
		}catch(e){
			try{
				//如果是IE6的版本
				return new ActiveXObject("Msxml2.XMLHTTP");
				
			}catch(e){
				try{
					//如果是IE5.5版本
					return new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){
					alert("亲,你这是什么浏览器啊!");
				}
			}
		}
	} 
</script>
<body>

<h3>注册页面</h3>
<form action="" method="post">
	姓名:<input type="text" name="username" id="nameId" onblur="run()"/><span id="uSpan"></span></br>
	密码:<input type="password" name="password"/></br>
	<input type="submit" name="注册"/>
</form>


</body>
</html>

UserServlet:

package demo1;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 接收请求参数
		 * 去数据库中查询
		 * 	如果能查询到,说明数据库中已存在该用户,不能注册
		 *  如果查询不到,说明数据库中不存在该用户,可以注册
		 */
		//有可能乱码
		request.setCharacterEncoding("utf-8");
		//响应中文
		response.setContentType("text/html;charset=utf-8");
		
		String username=request.getParameter("username");
		System.out.println(username);
		
		//写死
		//如果输入admin,提示用户名已经存在了
		if("admin".equals(username)){
			response.getWriter().print("<font color=‘red‘>亲,该用户已经存在了</font>");
		}else{
			response.getWriter().print("<font color=‘green‘>亲,可以注册</font>");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

  

**json数据格式的概述**

  1.json的概述:js提供一种数据交换的数据的格式。一般的情况下,都是在后台的拼接成json数据,响应的前台。使用js代码就非常方便操作json。
  2.json数据格式的规范
    * 定义json数据 格式必须使用{}括起来,对外提供的方式就是对象。
    * 例如:var person = {}; 成为json数据的格式 person提供对象的方式

    * 对象包含属性和值,如果是属性,必须是双引号括起来,要求:不能使用单引号。
    * var person = {"name":"张三","age":18,"love":["篮球","足球"]};

    * 值可以出现的类型?
      * null
      * 数字
      * 字符串
      * 数组 使用[]括起来
      * boolean true或者false

  3.定义json的格式的规范
    * var person = {"name":"zhangsan","age":18};
    * 包含属性和属性值之间使用 冒号(:)
    * 属性与属性之间是 逗号(,)
    * 获取属性的值 person.name 或者 person.age

  4.完成前后台的交互
    * 从后台发送json数据格式的数据。在前台使用js解析数据。

  5.从后台响应的json格式的数据,到前台使用eval函数执行一次。
    * 使用eval函数 全局函数,可以执行js的代码 并且执行的时候拼接小括号
    * 例如:var msg = eval("("+text+")");
    * 必须要使用eval的函数,执行后的结果才是json对象。

 

最基本的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>
</head>
<script type="text/javascript">
	//定义json格式的数据,必须使用{} 括起来,对外提供的就是对象的方式了
	var p={"name":"张三","age":18};
	alert(p.name);
	alert(p.age);
	
	//定义复杂的json
	var p2=[{"name":"赵四","age" :19},{"name":"王五","age":20}];
	//获取值
	alert(p2[0].name);
	
	var p3={"stu":[{"name":"赵四","age" :19},{"name":"王五","age":20}]};
	alert(p3.stu[1].age);

</script>
<body>

</body>
</html>

 

前后台交互的json:

Json1Servlet:

/**
 * 服务器端生成的json格式的数据,响应到客户端上
 * @author mjl
 *
 */
public class Json1Servlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("请求成功");
		//手动拼接json格式的字符串,响应回去
		String p="{\"name\":\"tom\",\"age\":18}";
		response.getWriter().print(p);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}
}

json2.jsp:

<%@ 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>
</head>
<script type="text/javascript">
	function run(){
		
		var xhr=createXMLHttpRequest();
		xhr.open("GET","${pageContext.request.contextPath}/json1",true);
		xhr.send(null);
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4 && xhr.status==200){
				var p1=xhr.responseText;
				//必须使用eval函数执行一次,变成json的对象
				
				//全局函数,可以直接使用
				var p2=eval("("+p1+")");
				
				alert(p2.name);
				alert(p2.age);
			}	
		}
	}
	
	
	function createXMLHttpRequest(){
		try{
			//如果你是IE高版本 火狐 谷歌
			return new XMLHttpRequest();
		}catch(e){
			try{
				//如果是IE6的版本
				return new ActiveXObject("Msxml2.XMLHTTP");
				
			}catch(e){
				try{
					//如果是IE5.5版本
					return new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){
					alert("亲,你这是什么浏览器啊!");
				}
			}
		}
	} 
</script>
<body>

<h3>json数据格式</h3>
<input type="button" value="点我" onclick="run()"/>
</body>
</html>

  

**jsonlib工具类的使用**

  1.作用:后台提供的工具类,可以把JavaBean转换成json数据格式的字符串。
  2.JSON-LIB开源的jar包。
    * 导入相应的jar包。

  3.记住这两个类
    * JSONObject
      * 把该类当成Map集合来记。
      * 提供的一些方法
        * put(key,value)
        * 静态方法:fromObject(JavaBean)传入进去,返回的JSONObject类
        * 都有一个toString()方法,把JSONObject转换字符串的json的数据格式

    * JSONArray
      * 把该类当成List集合来记。
        * add(JavaBean) -- 返回的类似数组的json格式。
        * toString() -- 把JSONArray转发字符串json数据格式

4.总结
  * jsonlib工具类目的,在服务器端把对象转换成json格式的字符串。
  * 提供了两个类
    * JSONObject
      * put(key,value)
      * 静态方法,fromObject(Object)
      * toString(),转换json格式的字符串

      * JSONArray
      * add()
      * toString(),转换json格式的字符串

/**
 * 演示jsonlib工具类的使用
 * @author mjl
 *
 */
public class JsonDemo {

	/**
	 * 演示方法
	 * JSONObject的put方法
	 */
	@Test
	public void run1(){
		//创建JSONObject对象
		JSONObject j=new JSONObject();
		//调用put方法
		j.put("name", "张三");
		j.put("age", 18);
		//生成json格式的字符串
		String msg=j.toString();
		//响应msg
		System.out.println(msg);
	}
	
	/**
	 * 把Product对象转换成json格式的字符串
	 * var pp={"p":{"pname":"故事会","price":10}}
	 * alert(pp.p.pname);
	 */
	@Test
	public void run2(){
		JSONObject j=new JSONObject();
		Product p=new Product("故事会",10);
		//生成json格式的数据
		j.put("p", p);
		//生成json格式的字符串
		String msg=j.toString();
		//响应msg
		System.out.println(msg);
	}
	
	/**
	 * 把对象转成json格式的字符串
	 * var p={"pname":"故事会","price":10}
	 * p.pname
	 */
	@Test
	public void run3(){
		Product p=new Product("故事会",10);
		JSONObject j=JSONObject.fromObject(p);
		//生成json格式的字符串
		String msg=j.toString();
		//响应msg
		System.out.println(msg);
	}
	
	/**
	 * var p=[{"pname":"故事会","price":10},{"pname":"编程思想","price":90}]
	 * p[0].pname
	 */
	@Test
	public void run4(){
		Product p=new Product("故事会",10);
		Product p1=new Product("编程思想",90);
		JSONArray j=new JSONArray();
		
		//调用add方法
		j.add(p);
		j.add(p1);
		
		String msg=j.toString();
		System.out.println(msg);
	}
}

  

  

  

  

  

  

11.Ajax JSON

原文:https://www.cnblogs.com/syj1993/p/8460382.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!