使用AJAX,Spring MVC,MySQL更新表

时间:2015-12-28 00:08:11

标签: jquery mysql ajax spring spring-mvc

如何在foreach循环中使用AJAX更新我的表而不刷新页面! 请帮忙! 这是我的jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %>
<%@page language="java" session="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Cообщения | Violence and Hate</title>
<link href="<c:url value="/resources/bootstrap/bootstrap.css"/>"
	rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/bootstrap/bootswatch.less.css"/>"
	rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/bootstrap/variables.less.css"/>"
	rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/CSS/styles.css"/>" rel="stylesheet"
	type="text/css">
<script src="<c:url value="/resources/Jquery/jquery-2.1.4.min.js"/>"
	type="text/javascript"></script>
</head>
<body>

	<nav class="navbar navbar-default">
		<div class="container-fluid">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed"
					data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">Violence and Hate</a>
			</div>

			<div class="collapse navbar-collapse"
				id="bs-example-navbar-collapse-1">
				<ul class="nav navbar-nav">

					<li><a href="/app/user">Профиль</a></li>
					<li><a href="/app/user/messages">Сообщения</a></li>
					<li><a href="/app/user/search">Поиск оппонента</a></li>
					<li class="dropdown"><a href="#" class="dropdown-toggle"
						data-toggle="dropdown" role="button" aria-expanded="false">Информация<span
							class="caret"></span></a>
						<ul class="dropdown-menu" role="menu">
							<li><a href="/app/user/rules">Правила</a></li>
							<li><a href="/app/user/contacts">Наши контакты</a></li>
							<li class="divider"></li>
							<li><a href="/app/user/feedback">Написать администрации</a></li>
						</ul></li>
					<security:authorize ifAnyGranted="ROLE_ADMIN">
						<li class="dropdown"><a href="#" class="dropdown-toggle"
							data-toggle="dropdown" role="button" aria-expanded="false">Администрирование<span
								class="caret"></span></a>
							<ul class="dropdown-menu" role="menu">
								<li><a href="/app/admin">Админка/Список пользователей</a></li>
								<li><a href="/app/admin/feedbacklist">Отзывы/Вопросы/Предложения</a></li>

							</ul></li>
					</security:authorize>
				</ul>

				<c:url var="logoutUrl" value="/j_spring_security_logout" />
				<form class="navbar-form navbar-right" action="${logoutUrl}"
					method="post">
					<button class="btn btn-default" type="submit">Выйти</button>
					<input type="hidden" name="${_csrf.parameterName}"
						value="${_csrf.token}" />
				</form>
			</div>
		</div>
	</nav>
	<img class="img-responsive center-block"  src="<c:url value="/resources/logo/logo.png"/>" />
	<h2 class="text-center">Личные сообщения</h2>
<h5 class="text-center">Чтобы начать общение - выберите оппонента в поиске и отправьте ему сообщение</h5>

   <!-- tabs left -->
   <c:if test="${!empty listDialog}">
      <div class="tabbable tabs-left">

        <ul class="nav nav-tabs">
        <li class="active"><a href="#start" data-toggle="tab">Инфо</a></li>
      <c:forEach items="${listDialog}" var="dialog"> 
          <li><a href="#a" data-toggle="tab">${dialog.iddialog}</a></li>
          </c:forEach>      
        </ul>
        
        <div class="tab-content">
        <!-- <div class="tab-pane active" id="start">
        Напишите сообщение через поиск!
        </div>
         <div class="tab-pane"  id="a">Lorem ipsum dolor sit amet, charetra varius quam sit amet vulputate. 
         Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero.</div>
        </div>-->
      </div>
      <!-- /tabs -->
    </div>
</c:if>
</body>
<script src="<c:url value="/resources/Jquery/jquery-2.1.4.min.js"/>"
	type="text/javascript"></script>
<script src="<c:url value="/resources/bootstrap/bootstrap.js"/>"
	type="text/javascript"></script>
</html>

这是我的控制器方法,我从数据库中获取对话框列表

@RequestMapping(value = "/user/messages", method = RequestMethod.GET)
public String messagesPage(Model model, Principal principal) {
    model.addAttribute("dialog", new Dialog());
    model.addAttribute("listDialog", dialogService.listDialog(principal.getName()));
    return "messages";

}

这是我的DAO方法,我使用SQL查询从数据库中获取信息

@SuppressWarnings("unchecked")
@Override
public List<Dialog> listDialog(String username) {
    String query = "select dialog.iddialog, dialog.username, dialog.reciever from dialog where dialog.username LIKE '%s' OR dialog.reciever LIKE '%s'";
    Session session = null;
    session = sessionFactory.openSession();
    List<Dialog> dialogList = session.createSQLQuery(String.format(query, username, username)).addEntity(Dialog.class).list();
    session.close();
    session = null;
    return dialogList;
}

这是我的带有用户表和对话表的SQL代码

    CREATE TABLE `users` ( 
`username` varchar(45) CHARACTER SET utf8 NOT NULL, 
`enabled` bit(1) NOT NULL,
`password` varchar(60) CHARACTER SET utf8 NOT NULL, 
`name` varchar(30) CHARACTER SET utf8 NOT NULL,
`surname` varchar(30) CHARACTER SET utf8 NOT NULL,
`email` varchar(50) CHARACTER SET utf8 NOT NULL,
`gender` varchar(30) CHARACTER SET utf8 NOT NULL,
`age` varchar(2) NOT NULL,
`weight` varchar(2) NOT NULL,
`height` varchar(3) NOT NULL,
`sport` varchar(50) CHARACTER SET utf8 NOT NUlL,
`place` varchar(400) CHARACTER SET utf8 NOT NULL,
`photoa` varchar(100) NOT NULL,
`photob` varchar(100) NOT NULL,
PRIMARY KEY (`username`) 
) ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

CREATE TABLE `user_roles` ( 
`user_role_id` int(11) NOT NULL auto_increment, 
`role` varchar(45) NOT NULL, 
`username` varchar(45) NOT NULL, 
PRIMARY KEY (`user_role_id`), 
KEY `FK_9ry105icat2dux14oyixybw9l` (`username`), 
CONSTRAINT `FK_9ry105icat2dux14oyixybw9l` FOREIGN KEY (`username`) REFERENCES `users` (`username`) 
) ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

create table dialog
(
`iddialog` int NOT NULL auto_increment,
`reciever` varchar(50) CHARACTER SET utf8 NOT NULL,
`username`varchar(45) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY(`iddialog`),
foreign key (`username`) references users(`username`)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

2 个答案:

答案 0 :(得分:0)

java方法很简单:

只返回你想要的数据结构并在声明中添加@ResponseBody(你需要在类路径中使用jackson):

@RequestMapping(value = "/user/messagesajax", method = RequestMethod.GET)
public @ResponseBody List<Dialog> messagesPageAjax(Model model, Principal principal) {
    return dialogService.listDialog(principal.getName());
}

然后你必须编写一个js函数并将其绑定到DOM事件(文档加载,按钮单击,...),该函数将如下所示(Jquery 1):

function ajaxFillTable() {

    $.ajax({
        dataType : "json",
        url : '/user/messagesajax',
        headers : {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        },
        type : 'GET',
        success : function(data) {
            //TODO FILL your table 
            $.each(data,function(key, val) {
                    //TODO
            });

        }
    });
}

在成功方法中,您将获得&#34;数据&#34;变量,你可以迭代列表,获取属性并将html附加到DOM

答案 1 :(得分:0)

我没有控制器就做到了。 1.创建了ajax脚本

        <script>
    function getDialogs()
    {
    $.ajax({ 
        type: 'GET',
        url: '/app/user/dialogs', 
        success: function(r) 
        { 
            $('#dialogs').html(r);

            console.log(r); 
        }, 
        error : function(r){ alert(r); }});
    }
    setInterval(getDialogs, 1000);

</script>

2。创建了dialogs.jsp并在那里推出了我需要更新的部分代码。这就是