zoukankan      html  css  js  c++  java
  • 使用Ajax向SpringMVC传递Json数据

    这篇文章已经过时了。

    请参考比较合适的前后端交互方式

    1、保证SpringMVC配置成功了。

    2、在pom.xml中追加Jackson相关的依赖

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

    3、网页追加JQuery

    <script type="text/javascript" src="/html/jquery-3.2.1.min.js"></script>

    script不能单标签自闭合

    注意src的路径,现在这个写法是以webapp出发的绝对路径

    4、SpringMVC的配置文件中为“注解驱动”追加消息转换器

        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                </bean>
                <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>

    至此为止,Ajax可用了

            $.ajax({
                type:"post",
                url:"/ajax/json_str",
                dataType:"json",
                contentType : 'application/json',
                data:JSON.stringify(saveData),
                success:function(data) {
                    alert(data);
                },
                error:function(data) {
                    alert('error');
                }
            });
            $.ajax({
                type:"post",
                url:"/ajax/json_obj",
                dataType:"json",
                data:saveData,
                success:function(data) {
                    alert(data);
                },
                error:function(data) {
                    alert('error');
                }
            });

    如果json对象被JSON.stringify转换成了json字符串,则一定要有contentType : 'application/json',

    如果json对象的话,则不能有contentType : 'application/json'

  • 相关阅读:
    开源项目
    测试面试话题8:测试人员如何让开发少写bug?
    其他
    接口平台
    001接口概念
    python3PIL模块实现图片加文字/小图片水印
    python3实现url编码/解码
    python3实现读取Excel进行接口自动化测试
    常用正则表达式
    Python3实现简单的接口性能测试
  • 原文地址:https://www.cnblogs.com/deolin/p/7198776.html
Copyright © 2011-2022 走看看