AJAX和JSON

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX和JSON相关的知识,希望对你有一定的参考价值。

1 AJAX

1.1 AJAX简介

  • AJAX:Asynchronous javascript And XML,异步的JavaScript和XML。
  • 一种非常流行的web编程方式:
    • ①更好
    • ②更快
    • ③用户体验更好  
  • AJAX不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的web应用程序的技术,是基于JavaScript、xml、html和CSS的新用法。

 

1.2 传统的web模型和AJAX交互模型

技术分享

1.3 AJAX的编码步骤

  • ①创建XMLHttpRequest对象
  • ②注册状态监控回调函数
  • ③建立与服务器的异步连接
  • ④发出异步请求

 

  • 全站编码过滤器
package com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class EncodingFilter implements Filter {
    private FilterConfig config;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        String encoding = config.getInitParameter("encoding");
        if(encoding == null){
            encoding = "utf-8";
        }

        HttpServletRequest request = null;
        HttpServletResponse response = null;
        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) resp;
        }catch (Exception e){
            throw new RuntimeException("不是Http请求的request和response");
        }
        //解决POST请求和响应信息的字符输出流
        request.setCharacterEncoding(encoding);
        response.setContentType(encoding);
        response.setContentType("text/html;charset="+encoding);

        //如果是get请求提交,需要对request进行装饰包装
        HttpServletRequestD httpServletRequestD = new HttpServletRequestD(request);

        chain.doFilter(httpServletRequestD, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

}
class HttpServletRequestD extends HttpServletRequestWrapper{

    public HttpServletRequestD(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        try {
            //在tomcat8中的编码使用的是utf-8,所以对get请求不需要处理,但如果是tomcat6那么就需要将iso8859-1转变为utf-8
            value = new String(value.getBytes(super.getCharacterEncoding()),super.getCharacterEncoding());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {

        String[] values = super.getParameterValues(name);
        String[] newValue = new String[values.length];
        for(int x = 0;x<values.length;x++){//对每一个字符串都进行编码转换
            String value = values[x];
            try {
                value = new String(value.getBytes(super.getCharacterEncoding()),super.getCharacterEncoding());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            newValue[x] = value;
        }



        return newValue;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>com.filter.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

 

  • 示例:GET请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX编码步骤</title>
    <script type="text/javascript">
        window.onload =function () {
            //GET方式提交
            //我们知道GET方式提交的参数是在请求头
            document.getElementById("btn").onclick = function () {
                var input_value = document.getElementById("input_value").value;

                //1.创建XMLHttpRequest对象
                var xmlhttp ;
                if(window.XMLHttpRequest){
                    xmlhttp = new XMLHttpRequest();
                }else{
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                //注册状态监控回调函数
                xmlhttp.onreadystatechange= function () {
                    if(xmlhttp.readyState == 4){
                        if(xmlhttp.status == 200){
                            var text = xmlhttp.responseText;
                            alert(text);

                        }
                    }
                }
                //建立与服务器的异步连接
                xmlhttp.open("GET","/ajax?name="+input_value);
                //发出异步请求 发出请求体
                xmlhttp.send(null);

            }



        }



    </script>
</head>
<body>
    <input type="text" id="input_value"/>
    <input type="button" value="点击" id="btn"/>

 </body>
</html>
package com.controller;

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

@WebServlet(name = "AjaxServlet",urlPatterns = "/ajax")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println(name);
        response.getWriter().println(name);

    }

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

 

  • 示例:POST请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX编码步骤</title>
    <script type="text/javascript">
        window.onload =function () {
            //POST方式提交
            //我们知道POST方式提交的参数是在请求体
            document.getElementById("btn").onclick = function () {
                var input_value = document.getElementById("input_value").value;

                //1.创建XMLHttpRequest对象
                var xmlhttp ;
                if(window.XMLHttpRequest){
                    xmlhttp = new XMLHttpRequest();
                }else{
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                //注册状态监控回调函数
                xmlhttp.onreadystatechange= function () {
                    if(xmlhttp.readyState == 4){
                        if(xmlhttp.status == 200){
                            var text = xmlhttp.responseText;
                            alert(text);

                        }
                    }
                }

                //建立与服务器的异步连接
                xmlhttp.open("POST","/ajax");
                //发出异步请求 发出请求体
                xmlhttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
                xmlhttp.send("name="+input_value);

            }



        }



    </script>
</head>
<body>
    <input type="text" id="input_value"/>
    <input type="button" value="点击" id="btn"/>

 </body>
</html>
package com.controller;

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

@WebServlet(name = "AjaxServlet",urlPatterns = "/ajax")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        System.out.println(name);
        response.getWriter().println(name);

    }

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

 

2 JSON

2.1 JSON简介

  • JSON是一种轻量级的的数据交换格式。易于人的阅读和编写,同时也易于机器解析和生成。。
  • JSON采用完全独立于语言的文本格式,但是也使用了类似C语言家族的习惯,这些特性使得JSON成为理想的数据交换格式。

 

2.2 JSON组成

  • json对象
{
    key1:value1,
    key2:value2,
    ...
}
  • json数组
[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]

 

2.3 使用json lib来java中常见对象转换为JSON

  • pom.xml
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>


    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.1</version>
    </dependency>


    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.8.3</version>
    </dependency>


    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>


    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>


    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>

 

  • Account.java--javabean
package com.domain;

import java.io.Serializable;
import java.util.Date;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name=‘" + name + ‘\\‘‘ +
                ", money=" + money +
                ‘}‘;
    }
}

 

  • 示例:将java数组转换成json数组
 @Test
    public void testArray(){
        String[] str = {"aa","bb","cc"};
        JSONArray jsonArray = JSONArray.fromObject(str);
        System.out.println(jsonArray);
    }

 

  • 示例:将java的List集合转换为json数组
@Test
    public void testList(){
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray);
    }

 

  • 示例:将java对象转换为json对象
@Test
    public void testObject(){
        Account account = new Account();
        account.setId(1);
        account.setName("哈哈");
        account.setMoney(230.0);
        JSONObject jsonObject = JSONObject.fromObject(account);
        System.out.println(jsonObject);
    }

 

  • 示例:在将java对象转换为json对象的过程中,过滤掉一些不想要的信息
 @Test
    public void testObjectWithoutName(){
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"name"});
        Account account = new Account();
        account.setId(1);
        account.setName("哈哈");
        account.setMoney(230.0);
        JSONObject jsonObject = JSONObject.fromObject(account,config);
        System.out.println(jsonObject);
    }

 

  • 示例:将java的set集合转换为json数组
 @Test
    public void testSet(){
        Set<Account> set = new HashSet<>();

        Account a = new Account();
        a.setId(1);
        a.setName("aaa");
        a.setMoney(100.0);

        Account b = new Account();
        b.setId(2);
        b.setName("bbb");
        b.setMoney(200.0);

        set.add(a);
        set.add(b);

        JSONArray jsonArray = JSONArray.fromObject(set);
        System.out.println(jsonArray);

    }

 

  • 示例:将Map集合转换为json对象
 @Test
    public void testMap(){
        Map<String,Object> map = new HashMap<>();

        map.put("aaa","aaaaa");
        map.put("bbb","bbbbb");

        JSONObject object = JSONObject.fromObject(map);
        System.out.println(object);

    }

 

3 AJAX和JSON的案例

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX编码步骤</title>
    <script type="text/javascript">
        window.onload =function () {
            //POST方式提交
            //我们知道POST方式提交的参数是在请求体
            document.getElementById("btn").onclick = function () {

                //1.创建XMLHttpRequest对象
                var xmlhttp ;
                if(window.XMLHttpRequest){
                    xmlhttp = new XMLHttpRequest();
                }else{
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                //注册状态监控回调函数
                xmlhttp.onreadystatechange= function () {
                    if(xmlhttp.readyState == 4){
                        if(xmlhttp.status == 200){
                            var text = xmlhttp.responseText;
                            var json = eval("("+text+")");
                            var html = "";
                            for(var x =0;x<json.length;x++){
                                var account = json[x];
                                var account_id = account.id;
                                var account_name = account.name;
                                var account_money = account.money;
                                html +="<tr><tb>"+account_id+"</tb>";
                                html +="<tb>"+account_name+"</tb>";
                                html +="<tb>"+account_money+"</tb></tr>";
                            }
                            document.getElementById("tbody").innerHTML = html;

                        }
                    }
                }

                //建立与服务器的异步连接
                xmlhttp.open("POST","/ajax");
                //发出异步请求 发出请求体
                xmlhttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
                xmlhttp.send(null);

            }



        }



    </script>
</head>
<body>

    <input type="button" value="点击" id="btn"/>

    <table bgcolor="#faebd7" >
        <tbody id="tbody"></tbody>
    </table>

 </body>
</html>
  • AjaxServlet.java
package com.controller;

import com.domain.Account;
import net.sf.json.JSONArray;

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

@WebServlet(name = "AjaxServlet",urlPatterns = "/ajax")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Account> accounts = new ArrayList<>();

        Account a = new Account();
        a.setId(1);
        a.setName("aaa");
        a.setMoney(100.0);

        Account b = new Account();
        b.setId(2);
        b.setName("bbb");
        b.setMoney(200.0);

        accounts.add(a);
        accounts.add(b);

        JSONArray array = JSONArray.fromObject(accounts);

        response.getWriter().println(array.toString());



    }

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

 

以上是关于AJAX和JSON的主要内容,如果未能解决你的问题,请参考以下文章

AJAX相关JS代码片段和部分浏览器模型

微信授权页面执行ajax不执行,刷新才能执行

错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”

如何使用 extJS 发布 json 数据

json 个人的vscode的代码片段

实用代码片段将json数据绑定到html元素 (转)