编程练习

来源:3-6 自由编程

一娆Hacker

2021-05-13 15:43:54

servlet

package com.imooc.ajax;

import com.alibaba.fastjson.JSON;

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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/musiclist")
public class MusicServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List pops=new ArrayList();
pops.add("稻香");
pops.add("晴天");
pops.add("告白气球");
List gos=new ArrayList();
gos.add("千千厥歌");
gos.add("傻女");
gos.add("七友");
List rocks=new ArrayList();
rocks.add("一块红布");
rocks.add("假行僧");
rocks.add("新长征路上的摇滚");
String music=request.getParameter("music");
String json=null;
if(music!=null&&music.equals("pop")){
json=JSON.toJSONString(pops);
}else if(music!=null&&music.equals("gos")){
json=JSON.toJSONString(gos);
}else if(music!=null&&music.equals("rock")){
json=JSON.toJSONString(rocks);
}
System.out.println(json);
response.setContentType("text/html;charset=utf-8");
response.getWriter().println(json);

}
}

html

<!--<!DOCTYPE html>-->
<!--<html>-->
<!--<head>-->
<!-- <meta charset="UTF-8">-->
<!-- <title>Title</title>-->
<!--</head>-->
<!--<body>-->
<!--<div style="width:100%">-->
<!-- <input style="width: 20%" type="button" id="emp" name="emp" value="员工列表">-->
<!-- <input style="width: 20%" type="button" id="pos" name="pos" value="职位列表">-->
<!-- <input style="width: 20%" type="button" id="dep" name="dep" value="部门列表">-->
<!--</div>-->
<!--</body>-->
<!--</html>-->

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery-3.6.0.js"></script>
</head>
<body>
<div style="text-align: center">
<button style="width: 30%" value="pop">流行歌曲</button>
<button style="width: 30%" value="gos">经典歌曲</button>
<button style="width: 30%" value="rock" >摇滚歌曲</button>
</div>
<div style="text-align: center" id="content">

</div>
</body>
<script type="text/javascript">
$("button").click(function (){
var val=$(this).val();
$.ajax({
"url":"/ajax/musiclist",
"type":"get",
"data":{"music":val},
"dataType":"json",
"success":function (json){
console.log(json);
var html="";
for(var i=0;i<json.length;i++){
html+=json[i]+"<br>";
}
$("#content").html(html);
}
})
})
</script>
</html>


写回答

1回答

好帮手慕阿园

2021-05-13

同学你好,测试代码完成的不错,继续加油

祝学习愉快~

0

0 学习 · 16556 问题

查看课程

相似问题

编程练习

回答 1

编程练习

回答 1

编程练习

回答 1

编程练习

回答 2

编程练习

回答 1