Json和Ajax学习

Posted 轻舟一曲

tags:

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

JSON和AJAX

预备知识:

  • springMVC

    • Controller
    • springmvc配置文件
    • web.xml
  • javascript

    • 引入javaScript

web1.0:登录失败需要刷新页面才能重新登录,没有异步刷新,局部刷新功能。不点击提交按钮就不知道自己错了,还有手机号重复没有提示。

**web2.0:**最重要因素之一Ajax


Json

概述

  • 对象表示为键值对
  • 数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

JSON是JS对象的字符串表示法,本质是字符串。

var obj=a:'hello',b:'word';//js对象

var json='"a":"hello","b":"world"';//json字符串

转换

JSON字符串–>JS对象

var obj=JSON.parse('"a":"hello","b":"world"')

JS对象–>JSON字符串

var json=JSON.stringify(a:'hello',b:'word');

前后端分离,数据交互变得异常重要,JSON在效率方面很好。

<script>
    //编写一个对象
    let user=
        name:"吕布",
        age:2000,
        sex:"男"
    ;//输出
    console.log(user);
    //js对象---》转换为json字符串
    let json=JSON.stringify(user);
    console.log(json);
    console.log(JSON.parse(json));
</script>

抓取百度服务器响应地址:

查看网页源代码:

 sugHost : "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",

Controller返回Json

导入环境依赖:spring-webmvc

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>

静态资源过滤问题:

 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

编写springmvc-servlet.xml配置文件:注意归类时候可能不被web.xml识别

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--   自动扫描包交由Ioc容器管理-->
    <context:component-scan base-package="com.mf.controller"/>
    <!--    视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--  JSON乱码问题配置-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>

编写web.xml配置文件

    <!--    dispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--    Filter过滤器-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

导入fackjson包

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.4</version>
    </dependency>

编写controller

@Controller
public class UserController 

    @RequestMapping("/json1")
    //RequestMapping正常返回会走视图解析器,而json只需要返回json字符串而已
    //使用三方工具:Jackson,fastjson
    //@ResponseBody将服务器返回的对象转换为json对象返回
    @ResponseBody
    public String json1() throws JsonProcessingException 
        //需要Jackson的对象映射器,将对象转换成字符串
        ObjectMapper mapper = new ObjectMapper();
        //创建对象
        User user = new User("上官婉儿", 1, "女");
        System.out.println(user);
        //将对象转为字符串
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
        return  json;//不会转到视图解析器
    
    //如果有前端输出有乱码问题
    @RequestMapping(value = "/json2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json2() throws JsonProcessingException 
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(new User("上官婉儿", 1, "女"));
    


乱码问题统一配置文件解决

输出list集合

    @RequestMapping(value = "/json3")
    @ResponseBody
    public String json3() throws JsonProcessingException 
        List<User> list = new ArrayList<>();
        list.add(new User("上官婉儿1", 1, "女"));
        list.add(new User("上官婉儿2", 2, "女"));
        list.add(new User("上官婉儿3", 3, "女"));
        list.add(new User("上官婉儿4", 4, "女"));

        return new ObjectMapper().writeValueAsString(list);
    

JSON格式化:

date输出格式:时间默认返回json字符串变成时间戳格式

    @RequestMapping(value = "/time")
    @ResponseBody
    public String json4() throws JsonProcessingException 
        Date date = new Date();
        System.out.println(date);
        return new ObjectMapper().writeValueAsString(date);
    

前端输出时间戳:

解决:

    @RequestMapping(value = "/time2")
    @ResponseBody
    public String json5() throws JsonProcessingException 
        ObjectMapper mapper = new ObjectMapper();
        //1.如何不返回时间戳,关闭
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //2.如何解决时间格式化问题
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //3.指定mapper时间格式
        mapper.setDateFormat(dateFormat);
        Date date = new Date();
        System.out.println(dateFormat.format(date));
        return mapper.writeValueAsString(date);
    

重复代码封装成工具类

public class JsonUtils 
    //重载
    public static String getJson(Object object) throws JsonProcessingException 
        return getJson(object,"yyyy-MM-dd HH-mm-ss");
    
    public static String getJson(Object object,String format) throws JsonProcessingException 
        ObjectMapper mapper = new ObjectMapper();
        //1.如何不返回时间戳,关闭
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //2.如何解决时间格式化问题
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        //3.指定mapper时间格式
        mapper.setDateFormat(dateFormat);

        return mapper.writeValueAsString(object);
    


    @RequestMapping(value = "/time3")
    @ResponseBody
    public String json6() throws JsonProcessingException 
        return JsonUtils.getJson(new Date());
    

    @RequestMapping(value = "/json7")
    @ResponseBody
    public String json7() throws JsonProcessingException 
        List<User> list = new ArrayList<User>();
        list.add(new User("上官婉儿1", 1, "女"));
        list.add(new User("上官婉儿2", 2, "女"));
        list.add(new User("上官婉儿3", 3, "女"));
        list.add(new User("上官婉儿4", 4, "女"));

        return JsonUtils.getJson(list);
    

小结

异步数据交互:

@ResponseBody注解将对象转换位json字符串直接返回不走视图解析器;

@RequestBody则用来接收前台json字符串转换java对象。

Ajax

概述

使用Ajax创建动态性极强Web页面:当在搜索框输入关键字时候,JS将字符发送服务器返回搜索建议列表,增强B/S体验性。

用途:

  • 注册时,输入用户名自动监测用户是否存在;
  • 登录时,提示用户名和密码错误;
  • 删除数据行,行id发送到后台在数据库删除后在页面dom也删除数据行。

iframe

前端伪造ajax。

<head>
    <meta charset="UTF-8">
    <title>iframe</title>
    <style>
        .div1
            width: 300px;
            height: 200px;
            margin: 20px auto;
            background: url("../resources/1.jpg") 0 0 no-repeat;
            opacity: 0.7;
        
        iframe
            width: 100%;
            height: 500px;
        
        h3
            text-align: center;
        
        p
            margin-top: 10%;
            Ajax异步操作和Json的相关学习

Json和Ajax学习

Json和Ajax学习

ajax请求返回json数据--Go语言学习笔记

JAVAWEB学习笔记28_jqueryAjax:json数据结构jquery的ajax操作和表单校验插件

初学JSON和AJAX心得透过解惑去学习