请看下是否需要优化,答案五花八门,好多都看不懂
1、音乐列表显示: musicList.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" style="width: 33%" id="liuxing" value="流行歌曲"/>
<input type="button" style="width: 33%" id="jingdian" value="经典歌曲"/>
<input type="button" style="width: 33%" id="yaogun" value="摇滚歌曲"/>
<div style="width:240px;margin:auto" id="show"></div>
<script type="text/javascript" src="js/jquery-3.5.0.js"></script>
<script type="text/javascript">
var type;
$(function(){
$("input").on("click",function(){
type=$(this).attr("value");
$.ajax({
"url":"/ajax/song",
"type":"get",
"data":{"type":type},
"dataType":"json",
"success":function(json){
console.log(json);
//$("#show").remove(); remove是清除元素,这里是要清空内容不是清除元素
$("#show").empty();
for(var i=0;i<json.length;i++){
var show=json[i];
$("#show").append("<h1>"+show.name+"</h1>");
}
}
})
})
})
</script>
</body>
</html>
2、javabean类 Song
package com.imooc.servlet;
public class Song {
private String name;
public Song() {
}
public Song(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3、servlet处理: SongServlet
package com.imooc.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class SongServlet
*/
@WebServlet("/song")
public class SongServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SongServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type=request.getParameter("type");
List list=new ArrayList();
System.out.println(type);
if(type!=null&&type.equals("流行歌曲")) {
list.add(new Song("稻香"));
list.add(new Song("晴天"));
list.add(new Song("告白气球"));
}else if(type!=null&&type.equals("经典歌曲")) {
list.add(new Song("千千阙歌"));
list.add(new Song("傻女"));
list.add(new Song("七友"));
}else if(type!=null&&type.equals("摇滚歌曲")) {
list.add(new Song("一块红布"));
list.add(new Song("假行僧"));
list.add(new Song("新长征路上的摇滚"));
}else {
System.out.println("type error");
}
response.setContentType("text/html;charset=utf-8");
String json=JSON.toJSONString(list);
response.getWriter().println(json);
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星