为什么ajax接收不到数据?

为什么ajax接收不到数据?

问题描述:

servlet产生了字符串格式的json数据,但是在页面ajax接收不到呢?浏览器控制台中没有显示

相关代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>图书后台管理</title>
    <link rel="stylesheet" href="../../css/index.css">
    <link rel="stylesheet" href="../../css/bootstrap.min.css">

</head>

<body>
<header>
    <div class="container">
        <nav>
            <a href="/page/bookList">图书信息管理</a>
        </nav>
        <nav>
            <a href="/page/categoryList">分类管理</a>
        </nav>

    </div>
</header>
<section class="banner">
    <div class="container">
        <div>
            <h1>图书管理系统</h1>
            <p>图书信息管理</p>
        </div>
    </div>
</section>
<section class="main">


    <div class="container">
        <form class="form-horizontal" action="" method="post">
            <div class="form-group" style="float: right;">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-primary">查询</button>&nbsp;&nbsp;&nbsp;
                </div>
            </div>
            <div class="form-group" style="float: right;width: 300px;">
                <div class="col-sm-8">
                    <input name="searchContent" class="form-control" id="searchContent"
                           placeholder="输入要查询的分类" style="width: 250px">
                </div>
            </div>
        </form>
    </div>
    <div class="container">

        <table class="table table-striped">
            <thead>
            <tr>
                <th>序号</th>
                <th>图书编号</th>
                <th>图书名称</th>
                <th>分类</th>
                <th>价格</th>
                <th>图书封面</th>
                <th>操作</th>

            </tr>
            </thead>
            <tbody>
            <c:forEach items="${bookList}" var="book" varStatus="idx">
                <tr id="tr1">
                    <td>${idx.index+1}</td>
                    <td>${book.bookId}</td>
                    <td>${book.bookName}</td>
                    <td>${book.bookCategory.categoryName}</td>
                    <td>¥<fmt:formatNumber pattern="0.00" value="${book.bookPrice}"></fmt:formatNumber></td>
                    <td><img style="width: 160px;height: 90px" src="../../img/${book.bookCover}"></td>
                    <td>
                        <a href="/updateBook?bookId=${book.bookId}">修改</a>
                        <a href="/deleteBook?bookId=${book.bookId}">删除</a>

                    </td>
                    <!--在循环显示数据时,此处的book0001可以用EL表达式进行替换-->

                </tr>
            </c:forEach>
            </tbody>
        </table>
    </div>
</section>
<section class="page">
    <div class="container">
        <div id="fatie">
            <a href="/page/addBook">
                <button>新建</button>
            </a>
        </div>
    </div>
</section>
<footer>
    copy@慕课网
</footer>
<script type="text/javascript" src="/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
    $("form").submit(function () {
        var searchContentValue = $("#searchContent").val();
        if (searchContentValue != "") {
            alert(searchContentValue)
            $.ajax({
                "url": "/searchBook",
                "type": "get",
                "data": "categoryName="+searchContentValue,
                "dataType": "json",
                "success": function (json) {
                    alert(json);
                    console.log(json);
                }
            })
        }
    })

</script>
</body>
</html>
package com.imooc.bookmanager.controller;

import com.alibaba.fastjson.JSON;
import com.imooc.bookmanager.entity.Book;
import com.imooc.bookmanager.service.BookServiceImpl;

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.List;

@WebServlet("/searchBook")
public class SearchBook extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求查询的分类参数
String categoryName = req.getParameter("categoryName");
String booksJSON;
/*if (categoryName == null||categoryName=="") {
//参数为空则跳转至bookList页面
req.getRequestDispatcher("/page/bookList").forward(req, resp);
} else {
List<Book> booksByCategoryName = new BookServiceImpl().getBooksByCategoryName(categoryName);
booksJSON = JSON.toJSONString(booksByCategoryName);
resp.getWriter().println(booksJSON);
}*/
List<Book> booksByCategoryName = new BookServiceImpl().getBooksByCategoryName(categoryName);
booksJSON = JSON.toJSONString(booksByCategoryName);
System.out.println(booksJSON);
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().println(booksJSON);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕阿满 2021-01-18 20:15:53

同学你好,测试同学的代码可以接收到数据,但是由于同学使用的submit提交,造成结果会一闪而过。如:

http://img1.sycdn.imooc.com//climg/60057ba609c4e3db07500192.jpg

这里建议改为button,另外在js中,建议将submit改为click(),如:

http://img1.sycdn.imooc.com//climg/60057be1097eff7a06330160.jpg

祝学习愉快~

  • 提问者 谁叫我这么坏 #1

    老师,我按照上面说的方法更改并把ajax方法内容写完整后,表格可以显示其他内容,但是显示不了图片

    http://img1.sycdn.imooc.com//climg/60059d5c094d381417540406.jpg

    下面是ajax代码

    $.ajax({
    "url": "/searchBook",
    "type": "get",
    "data": "categoryName=" + searchContentValue,
    "dataType": "json",
    "success": function (json) {
    $("tbody").empty();
    var html;
    for (var i = 0; i < json.length; i++) {
    html = html + "<tr id='tr${idx.index+1}' class='table-tr'>";
    html = html + "<td>"+(i+1)+"</td>";
    html = html + "<td>"+json[i].bookId+"</td>";
    html = html + "<td>"+json[i].bookName+"</td>";
    html = html + "<td>"+json[i].bookCategory.categoryName+"</td>";
    html = html + "<td>"+json[i].bookPrice+"</td>";
    html = html + "<td><img style='width: 160px;height: 90px' src='../img/'"+json[i].bookCover+"></td>";
    html = html + "<td>";
    html = html + "<a href='/updateBook?bookId="+json[i].bookId+"'>修改</a>";
    html = html + "<a href='/deleteBook?bookId="+json[i].bookId+"'>删除</a>";
    html = html + "</td>";
    html = html + "</tr>";
    }
    $("tbody").append(html);
    }
    });


    2021-01-18 22:38:38
  • 同学你好,图片无法显示可能是图片路径不正确造成额,建议同学可以按F12,查看浏览器控制台的报错并具体解决。如果是图片路径问题,建议同学根据项目结构目录正确加载图片路径,如果同学自己无法解决,请将具体报错以及项目结构展开截图贴一下。

    祝学习愉快~

    2021-01-19 10:30:21
  • 老师,根据你说的方法解决了,查看控制台这么显示的http://img1.sycdn.imooc.com//climg/6006eeb00939624903520035.jpg,查看代码发现是因为把路径地址多写了单引号,造成图片路径不正确了。

    另外,我发现ajax返回数据并且页面内容显示更新后,再查看网页源代码时,显示更新前的源代码和显示更新后的源代码没有变化呢?

    2021-01-19 22:40:53
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师