简体   繁体   English

如何通过 Ajax 从 Servlet 获取列表到 JSP

[英]How to get list from Servlet to JSP through Ajax

I have a piece of code in a servlet我在 servlet 中有一段代码

    response.setContentType("application/json");
    new Gson().toJson(list, response.getWriter());

I have a code in ajax我在 ajax 中有一个代码

$.ajax({
        url: '${pageContext.request.contextPath}/Sort',
        type: 'POST',
        dataType: "json",
        data: {
            value : value,
            name : name,
            lowestPrice : lowestPrice,
            highPrice: highPrice
        },
        success: function (response) {
            
        },
        error: function () {
        }
    });

I have a code in jsp我在 jsp 中有一个代码

<c:forEach var="x" items="${allProduct}">
                <div class="hover-all-product">
                    <a class="all-product-item" href="${pageContext.request.contextPath}/Product?id=${x.maLapTop}">
                        <div class="status-sale">-11%</div>
                        <div class="img-all-product-item"
                             style="background-image: url('${root}${x.linkHinh1}')">
                        </div>
                        <div class="status">HẾT HÀNG</div>
                        <div class="infor-all-product-item">
                                ${x.tenLaptop}
                        </div>
                        <div class="price-all-product-item">
                                ${x.giaBan}
                        </div>
                        <div class="sale-all-product-item">
                            <span class="origin-price">33.999.000đ</span> <span>11%</span>
                        </div>
                    </a>
                </div>
            </c:forEach>

How can I assign the value of list in servlet to allProduct in jsp through ajax如何将servlet列表的值分配给jspajax中的allProduct

Think of when which piece of code will run.想想哪段代码何时运行。

  1. There is the browser's request for the JSP.浏览器请求 JSP。 The JSP will create the HTML page which the browser will try to render, and inside that HTML page the browser will execute JavaScript. JSP 将创建浏览器将尝试呈现的 HTML 页面,并且在该 HTML 页面内,浏览器将执行 Z686155AF75A60EDD3.EZD08C
  2. JavaScript running in the browser will trigger the AJAX request, which goes back to the server to fetch data.在浏览器中运行的 JavaScript 将触发 AJAX 请求,该请求返回服务器获取数据。
  3. The AJAX request to fetch data will trigger the servlet on the server side to lookup and deliver the requested data获取数据的 AJAX 请求将触发服务器端的 servlet 查找并传递请求的数据
  4. It is the JavaScript in the browser, which - after AJAX has finished - needs to merge the obtained result into the (dynamic) HTML in the browser.就是浏览器中的JavaScript,在AJAX完成后,需要将得到的结果合并到浏览器中的(动态)HTML中。

So have a closer look at your JavaScript code to tackle the problem.因此,请仔细查看您的 JavaScript 代码以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM