zoukankan      html  css  js  c++  java
  • Java Web 项目学习(三) 发布帖子 AJAX

    AJAX

    - Asynchronous JavaScript and XML
    - 异步的JavaScript与XML,不是一门新技术,只是一个新的术语。
    - 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
    - 虽然X代表XML,但目前JSON的使用比XML更加普遍。
    - https://developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX

    示例

    • 首先,我们需要引入fastjson依赖
    • 写方法封装JSON对象 (这里在CommunityUtil类下),需要用fastjson依赖
      /**
           *  解析Json: 将参数封装成Json对象,然后转化字符串,得到JSON格式的字符串
           * @param code  编码
           * @param msg 提示信息
           * @param map 业务数据
           * @return
           */
          public static String getJSONString(int code, String msg, Map<String,Object> map){
              JSONObject json = new JSONObject();
              json.put("code",code);
              json.put("msg",msg);
              if(map != null){
                  for (String key: map.keySet()){
                      json.put(key,map.get(key));
                  }
              }
              return json.toJSONString();
      
          }
      
          public static String getJSONString(int code, String msg){
              return getJSONString(code,msg,null);
          }
      
          public static String getJSONString(int code){
              return getJSONString(code,null,null);
          }
      
      
          public static void main(String[] args) {
              Map<String , Object> map = new HashMap<>();
              map.put("name","张三");
              map.put("age",25);
              System.out.println(getJSONString(0,"ok",map));
          }
    • 写对应的Controller方法
      /**
           * AJAX 示例
           */
          @RequestMapping(path = "/ajax",method = RequestMethod.POST)
          @ResponseBody
          public String textAjax (String name, int age){
              System.out.println(name);
              System.out.println(age);
              return CommunityUtil.getJSONString(0,"操作成功!");
          }
    • 写HTML文件  使用jQuery发送AJAX请求.

      在项目resource/static/html/ajax-demo.html
      引入jQuery  <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script> 
      定义函数send(),调用$.post method = RequestMethod.POST方法对应,$.post  需要三个参数。
      1)访问的路径,
      2)向服务器提交的数据(JS的对象,JSON格式),
      3)声明回调函数  ————服务器响应浏览器后,浏览器会调,回调函数,并且将服务器返回的数据传给回调函数。即data为返回的数据

      Console 是JS的对象,用于 JavaScript 调试,输出在浏览器端。


      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>AJAX</title>
      </head>
      <body>
          <p>
              <input type="button" value="发送" onclick="send();">
          </p>
          <!-- 引入jquery -->
          <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
          <script>
              function send() {
                  // $.post  有三个参数
                  // 1访问的路径,
                  // 2向服务器提交的数据(JS的对象,JSON格式),
                  // 3声明回调函数  ————服务器响应浏览器后,浏览器会调,回调函数,并且将服务器返回的数据传给回调函数。即data为返回的数据
                  $.post(
                      "/community/alpha/ajax",
                      {"name":"张三", "age":25},
                      function (data) {
                          console.log(typeof (data));
                          console.log(data);
      
                          //将data转换为JS对象
                          data = $.parseJSON(data);
                          console.log(typeof (data));
                          console.log(data.code);
                          console.log(data.msg);
      
                      }
                  );
      
              }
          </script>
      </body>
      </html>
    • 启动服务访问 http://localhost:8080/community/html/ajax-demo.html   注意这里没有static路径,并且必须加.html,否则无法找到页面。
      检查,点击发送。就可以在无刷新页面的情况下,得到服务器返回的信息。


    实践:采用AJAX实现发帖功能

    DAO层

    1. 在DiscussPostMapper中,增加函数。

      @Mapper
      public interface DiscussPostMapper {
          //分页查询数据,查询的可能是多条信息,因此返回的是一个集合
      
          //userID针对个性化,搜索我查找的帖子,首页不会传Id,因此其实实现的是一个动态的sql
          //考虑到未来支持分页的可能性,mysql的分页十分简洁,加一个limit + 起始行行号offset  +  分页展示多少条数据limit
          List<DiscussPost> selectDiscussPosts (int userId, int offset, int limit);
      
          //为了显示页码(查询的总条数/分页展示数据的条数limit),因此定义函数查询总的数据条数。同样动态sql
          //参数之前加注解 @Param("") 起别名,如果只有一个参数,并且在<if>中使用,则必须要有别名
          // 若需要动态的拼一个条件(动态sql),且需要用的这个参数,并且方法有且只有一个参数,则必须要起别名!
          int selectDiscussPostRows(@Param("userId") int userId);
      
      
          //增加帖子的内容
          int selectDiscussPostRows(DiscussPost discussPost);
      }
    2. 在discusspost-mapper.xml 写

          <sql id="insertFields">
              user_id, title, content, type, status, create_time, comment_count, score
          </sql>
          <insert id="insertDiscussPostRows" parameterType="DiscussPost" resultType="int">
              insert into disscuss_post (<include refid="insertFields"></include>)
              values (#{userId}, #{title}, #{content}, #{type}, #{status}, #{createTime}, #{commentCount}, #{score})
          </insert>

    Service层

    DiscussPostService

        
        @Autowired
        private DiscussPostMapper discussPostMapper;
    
        @Autowired
        private SensitiveFilter sensitiveFilter;
    
        public int addDiscussPostRows(DiscussPost post){
            if (post==null) {
                throw new IllegalArgumentException("参数不能为空!");
            }
            //转移HTML 标记
            post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
            post.setContent(HtmlUtils.htmlEscape(post.getContent()));
            //过滤器
            post.setTitle(sensitiveFilter.filter(post.getTitle()));
            post.setContent(sensitiveFilter.filter(post.getContent()));
    
            return discussPostMapper.insertDiscussPostRows(post);
        }

    Controller层

    DisscussPsotController

    @Controller
    @RequestMapping("/disscuss")
    public class DisscussPsotController {
        @Autowired
        private DiscussPostService discussPostService;
    
        @Autowired
        private HostHolder hostHolder;   //获取当前用户
    
        @RequestMapping(path = "/add", method = RequestMethod.POST)
        public String addDiscussPost(String title, String content){
            User user = hostHolder.getUser();
            if (user == null){
                return CommunityUtil.getJSONString(403,"你还未登录!");
            }
            DiscussPost post = new DiscussPost();
            post.setUserId(user.getId());
            post.setTitle(title);
            post.setContent(content);
            post.setCreateTime(new Date());
            discussPostService.addDiscussPostRows(post);
            //报错情况,将来统一处理
            return CommunityUtil.getJSONString(0,"发布成功!");
    
    
        }
    
    }

    修改对应HTML
    index.html

  • 相关阅读:
    asp.net 连接 Access 的几种方法
    asp.net 连接 oracle10g 数据库
    Entity Framework实例
    LINQ链接数据库出错(There is already an open DataReader associated with this Command which must be closed first )
    Linq入门实例
    Nibatis实例(2)
    Log4net实例
    图片提交表单方法
    Nibatis实例(1)
    爱情是不离不弃吗?
  • 原文地址:https://www.cnblogs.com/codinghard/p/14868263.html
Copyright © 2011-2022 走看看