jsp和servlet数据传输

通过json,将数据显示在jsp中

jsp中:(这种遇到了输出在页面的时候出现undefined)

<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript">

function getCourse() {

//发送ajax请求
$.getJSON("../ShowCourseServlet",//产生JSON数据的服务端页面

{
"method":"getCourse",
},function(json){
console.log(json);//console.log()仅仅在控制台中打印相关信息
//循环取json中的数据
$.each(json,function(i){
$(".tit").append("

name:"+json[i].name+"

");
})
}
)
}

</script>

jsp中:

function getCourse() {
//发送ajax请求
$.getJSON("../ShowCourseServlet",{
"method":"course",
},function(json){
console.log(json);
var j;
//循环取json中的数据,并呈现在列表中
for(var i=0;ij=i+1;
$("#title"+j).append("

name:"+json.result[i].name+"

");
}
}
)
}
jsp中:

function getCourse() {
//发送ajax请求
$.getJSON("../ShowCourseServlet",{
"method":"course",
},function(json){
console.log(json);
var j;
//循环取json中的数据,并呈现在列表中
  for(var i=0;ij=i+1;
$("#course").append('

')
}  
})
}

特别注意json传入jsp时,json是个里面是数组的对象,所以用json.result[i].name

servlet中

    //输出流
    private void output(HttpServletResponse response,JSONObject json) throws IOException {
     response.setCharacterEncoding("UTF-8");
     response.setDateHeader("Expires", 0);
     response.setHeader("Cache-Control","no-cache");
     response.setHeader("Pragma","no-cache");
     PrintWriter out = response.getWriter();
     out.println(json);
     out.flush();
     out.close();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
System.out.println("method="+method);
if(method.equals("course")) {
getCourse(request,response);
}
if(method.equals("search")) {
searchCourse(request,response);
}
}
private void getCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
List courses = coursedao.getCourseList();
if(courses!=null && !courses.isEmpty()){
JSONArray jsonArray = JSONArray.fromObject(courses);
JSONObject json = new JSONObject();
json.put("result", jsonArray);
System.out.println("json="+json);
output(response,json);
}
}
    private void searchCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
     String courseName = request.getParameter("courseName");//获取用户填写的课程名
     List course = coursedao.getCourseListByCourseName(courseName);
     JSONArray jsonArray2 = JSONArray.fromObject(course);
     JSONObject json = new JSONObject();
     json.put("result", jsonArray2);
     System.out.println("json2="+json);
     output(response,json);
    }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

search搜索栏

  $("#course").empty(); 
var temp = document.getElementById('searchcourse').value;
$.getJSON("../ShowCourseServlet",{
"method":"search",
"courseName":temp
},function(json2){
console.log(json2);
  //循环输出每个课程div

你可能感兴趣的:(JavaWeb,servlet,jsp)