ajax实现页面不刷新前后台交互(完整前端代码)

注意:牵涉到的文件下载后,需要自行修改自己所放的位置。后台代码(后台生成json数据使用JSONArray和JSONObject,先将要转化的对象循环转化为JSONObject对象,同时循环再加入JSONArray)

后台简要提及需要处理:

response.setContentType("application/json; charset=utf-8");
response.setHeader("cache-control", "no-cache");

PrintWriter out = response.getWriter();

out.print(array.toString());
out.flush();
out.close();

也就是要将json数据返回给客户端.

(连接数据库和用户表映射类省略)

完整后台servlet代码:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import table.User;

/**
* Servlet implementation class Login
*/
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//实现登录
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
response.setContentType("application/json; charset=utf-8");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();


loginDao.Login login = new loginDao.Login();
JSONArray array = new JSONArray();

//如果查询的结果不为空,返回json数据给前端
try {
List<User> uList = login.login(uname, pwd);
if (uList!=null) {
for (int i = 0; i < uList.size(); i++) {
User user = uList.get(i);
JSONObject jsonObject = JSONObject.fromObject(user);
array.add(jsonObject);
System.out.println(array.toString());

}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(array.toString());
out.print(array.toString());
out.flush();
out.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

 

前台代码:

1、login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<!-- 引入js -->
<script src="./js/jquery-3.3.1.js"></script>
<script src="./js/getajax.js"></script>
<!-- 实现局部刷新 -->
<script src="./js\jquery-form.js"></script>
<script type="text/javascript">
var url_1 = "<%=basePath%>";
function getURL(){
return url_1;
}
$(document).ready(function() {
var options = {
//需要刷新的区域id
target:'.left',
};
//绑定FORM提交事件
$('#formId').submit(function() {
$(this).ajaxSubmit(options);
return false;
});

});
</script>
</head>
<body>

<div id="login">
<form action="<%=basePath%>Login" method="post" onsubmit="return toGo();" id="formId">
账号:<input type="text" name="uname" id="uname"/>
密码:<input type="password" name="pwd" id="pwd"/>
<input type="submit" value="提交">
</form>

</div>

<div class="left"></div>
<div class="left"></div>

 

</body>
</html>

 

2、getajax.js

function toGo(){


//异步加载json数据
$(function () {
var url_1 = getURL();

$.ajax({
url: url_1+'/Login?uname=cisco&pwd=1234',
type: 'post',
dataType: 'json',
timeout: 1000,
cache: false,
//async:false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction, //错误执行方法
success: succFunction //成功执行方法
});
function LoadFunction() {
$(".left").html('加载中...');
}
function erryFunction() {
alert("error");
}
function succFunction(tt) {
$(".left").html('');

//eval将字符串转成对象数组
//var json = { "id": "10086", "uname": "zhangsan", "email": "zhangsan@qq.com" };
//json = eval(json);
//alert("===json:id=" + json.id + ",uname=" + json.uname + ",email=" + json.email);

var json = eval(tt); //数组
var i = 0; //用于统计记录的条数,实现分页,点击下一页,则向前,初始状态为第一页
$(".left").html("" + json[0].uname + " " + json[0].pwd + " " + json[0].email + "");
$.each(json, function (index, item) {
//循环获取数据
i=i+1;
$(".left").html("" + json[index].uname + " " + json[index].pwd + " " + json[index].email + "");
});
}
});

}

posted @ 2019-02-17 20:22  CiscoLee  阅读(1171)  评论(0编辑  收藏  举报