老师,点击第一个按钮获取不到json数据是怎么回事

来源:3-6 自由编程

z晓龙

2019-07-26 22:25:23

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.btn{
	width: 33%;
}

.div1{
	text-align: center;
}

</style>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
	$("#fashion").click(function(){
		$.ajax({
			"url" : "/ajax/song",
			"type" : "get",
			"data" : {"t" : "fashion"},
			"dataType" : "json",
			"success" : function(json){
				console.log(json);
			}
		})
	})
</script>
</head>
<body>
	<input id="fashion" class="btn" type="button" value="流行歌曲" />
	<input id="classic" class="btn" type="button" value="经典歌曲" />
	<input id="rock" class="btn" type="button" value="摇滚歌曲" />
	<div id="container" class="div1"></div>
</body>
</html>

package com.imooc.practice;

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("t");
		List list = new ArrayList();
		if(type != null && type.equals("fashion")) {
			list.add(new Song("稻香"));
			list.add(new Song("晴天"));
			list.add(new Song("告白气球"));
		}else if(type != null && type.equals("classic")) {
			list.add(new Song("千千阙歌"));
			list.add(new Song("傻女"));
			list.add(new Song("七友"));
		}else if(type!= null || type.equals("rock")) {
			list.add(new Song("一块红布"));
			list.add(new Song("假行僧"));
			list.add(new Song("新长征路上的摇滚"));
		}else {
			System.out.println("无");
		}
		String json = JSON.toJSONString(list);
		System.out.println(json);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(json);
	}

}


写回答

1回答

好帮手慕阿莹

2019-07-27

同学你好,同学把js代码放到页面的最后试试,否则,当加载到js时,获取#fashion的时候,还没加载到html中的该元素。,放到页面的底部后,最后加载。就可以加载到了,再点击就有数据了。

http://img.mukewang.com/climg/5d3bad2e0001a91507990494.jpg


如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


0

0 学习 · 10204 问题

查看课程