> 文章列表 > JSON和AJAX

JSON和AJAX

JSON和AJAX

JSON

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON采用完全独立于语言的文本格式,而且很多语言都提供了对json的支持(包括C,C++,C#,Java,JavaScript,Perl,Python等〉。这样就使得JSON成为理想的数据交换格式。
     json是一种轻量级的数据交换格式。轻量级指的是跟xml做比较。数据交换指的是客户端和服务器之间业务数据的传递格式。

JSON在JavaScript的使用

<script>$(function(){var jsonObj = {"key1":1,"key2":'字符串',"key3":[2,3,4,5],"key4":{"j1":"j1_1","j2":"j2_3","j3":['j11','j22']},"key5":[{"k1":'k11'},{"k2":"k22"}]	 }console.log(jsonObj.key1);//1console.log(jsonObj.key2);//'字符串'console.log(jsonObj.key3.length+':第一个值:'+jsonObj.key3[0]);//2console.log(jsonObj.key4+'::::'+jsonObj.key4.j1);//j1_1console.log(jsonObj.key5+'::::'+jsonObj.key5[0].k1);//k11});</script>

json的两个常用的方法

                JSON.stringify()     json------------->字符串

                JSON.parse()        字符串------------>json对象

 JSON在JavaBean中的使用(使用了GSON工具类)

    //JavaBean 与 Json的转换@Testpublic void test1(){Person p1 = new Person(12,"小明");Gson gson = new Gson();String str = gson.toJson(p1);System.out.println(str);//{"age":12,"name":"小明"}Person person = gson.fromJson(str, new TypeToken<Person>(){}.getType());System.out.println(person);//Person{age=12, name='小明'}}//List 和 JSON 的转换@Testpublic void test2(){Person p1 = new Person(12,"小明");Person p2 = new Person(15,"小红");ArrayList<Person> list = new ArrayList<>();list.add(p1);list.add(p2);Gson gson = new Gson();String str = gson.toJson(list);System.out.println(str);ArrayList<Person> personList = gson.fromJson(str,new TypeToken<ArrayList<Person>>(){}.getType());System.out.println(personList);}//JSON 与 Map的转换@Testpublic void test3(){Person p1 = new Person(12,"小明");Person p2 = new Person(15,"小红");HashMap<Integer, Person> map = new HashMap<>();map.put(1,p1);map.put(2,p2);Gson gson = new Gson();String str = gson.toJson(map);System.out.println(str);HashMap<Integer, Person> personHashMap = gson.fromJson(str,new TypeToken<HashMap<Integer,Person>>(){}.getType());System.out.println(personHashMap);}

AJAX请求

 原生JS AJAX请求的示例

         

 JQuery Ajax请求

$.ajax请求

 $.get $post方法

                    url                          请求的url地址
                   data                        发送的数据
                   callback                 成功的回调函数
                   type                        返回的数据类型

 $.getJSON

表单序列化

                                           表单序列化serialize()
serialize()可以把表单中所有表单项的内容都获取到,并以name=value&name=value的形式进行拼接。

 总代码:jsp页面

<%--Created by IntelliJ IDEA.User: surfaceDate: 2023/3/23Time: 20:24To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>原生js的ajax请求</title><script src = "../static/jquery-2.1.4.js"></script><script>//这里使用javaScript语言发起Ajax请求,访问服务器function ajaxRequest(){//1 我们首先要创建XMLHttpRequestvar xmlHttpRequest = new XMLHttpRequest();//2 调用共open方法设置请求参数xmlHttpRequest.open("GET","http://localhost:8080/JavaWeb/ajaxServlet",true);//4 在send方法前绑定onreadystatechagne事件,处理请求完后完成的工作xmlHttpRequest.onreadystatechange = function (){if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){var jsonObj = JSON.parse(xmlHttpRequest.responseText);//数据显示document.getElementById("div1").innerText = jsonObj.age +':'+jsonObj.name;}};//3 调用send方法xmlHttpRequest.send();}function jQueryAjaxRequest(){$.ajax({url:"http://localhost:8080/JavaWeb/ajaxServlet",data:{action:"jQuery"},//参数列表type:"GET",success:function (data){//服务器返回的数据$('#div2').html(data.age+":"+data.name);},dataType:"json"//服务器返回的数据类型});}function getAjaxRequest(){//$.get(url,"参数列表",回调函数[返回的数据]{方法体});$.get("http://localhost:8080/JavaWeb/ajaxServlet","action=getJquery",function (data) {var str = JSON.stringify(data);$('#div3').text(str);},"json");}function postAjaxRequest(){$.post("http://localhost:8080/JavaWeb/ajaxServlet","action=getJquery",function (data) {$('#div4').text(data.age+':'+data.name);},"json");}function getJsonRequest(){$.getJSON("http://localhost:8080/JavaWeb/ajaxServlet","action=getJSON",function (data){var str = JSON.stringify(data);$('#div5').text(str);});}function getJsonSerialize(){$.getJSON("http://localhost:8080/JavaWeb/ajaxServlet",$('#form1').serialize(),function (data){$('#div6').text(data.age+':'+data.name+':'+data.hobby+':'+data.address);});}</script>
</head>
<body><button onclick="ajaxRequest()">ajax Request</button><div id="div1">div1</div><button onclick="jQueryAjaxRequest()">JQuery ajax Request</button><div id="div2">div2</div><button onclick="getAjaxRequest()">get JQuery ajax Request</button><div id="div3">div3</div><button onclick="postAjaxRequest()">post JQuery ajax Request</button><div id="div4">div4</div><button onclick="getJsonRequest()">getJSON ajax Request</button><div id="div5">div5</div><%--    serialize()可以把表单中所有表单项的内容都获取到,并以name=value&name=value的形式进行拼接。--%><button onclick="getJsonSerialize()">Serialize ajax Request</button><div id="div6">div5:表单序列化</div><br /><form id = form1><table><tr><td><input name = "hobby" value="篮球"></td><td><input name = "address" value="中国"></td></tr></table></form></body>
</html>

服务器中:servlet程序(使用了gson jar包)

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String hobby = req.getParameter("hobby");String address = req.getParameter("address");Person p1 = new Person(12,"小明",hobby,address);Gson gson = new Gson();String str = gson.toJson(p1);System.out.println(str);resp.setContentType("text/html; charset=UTF-8");//解决乱码问题在获取流之前resp.setStatus(200);resp.getWriter().write(str);}
}