简体   繁体   English

如何发送 JSP 作为对 AJAX 调用的响应

[英]How to send JSP as response to AJAX call

我想发送一个 JSP 页面,它由一些 div 和 table 组成,作为 Spring 框架的 AJAX 响应的一部分,有什么方法可以发送 JSP 作为 AJAX 调用的响应

Sending JSP by AJAX makes no sense, it is basically the HTML generated by a JSP that is sent over to the browser through AJAX, as rightly pointed out by the lost.通过 AJAX 发送 JSP 是没有意义的,它基本上是由 JSP 生成的 HTML 通过 AJAX 发送到浏览器,正如丢失的正确指出的那样。

You do not need any server-side coding for this.为此,您不需要任何服务器端编码。 All you need is to write some JavaScript on client-side to receive your HTML asynchronously.您所需要的只是在客户端编写一些 JavaScript 来异步接收您的 HTML。 For this, I would recommend using some JavaScript framework like jQuery, otherwise, it would make your life hell.为此,我建议使用一些 JavaScript 框架,如 jQuery,否则,它会让你的生活陷入困境。

Assuming that the page you want to access by AJAX has the link http://domain:port/mypage.htm .假设您要通过 AJAX 访问的页面具有链接http://domain:port/mypage.htm First you need to include jQuery in your base JSP (JSP in which former page has to load by AJAX):首先,您需要在您的基础 JSP 中包含 jQuery(其中前一个页面必须通过 AJAX 加载的 JSP):

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>

Then you need to call jQuery's AJAX function:然后需要调用jQuery的AJAX函数:

$(document).ready(function(){
    $.ajax({
        type:"GET",
        url: "http://domain:port/mypage.htm",
        success: function(data) {
            // Now you have your HTML in "data", do whatever you want with it here in this function         
            alert(data);
        }
    });
});

Hope it helps!希望能帮助到你!

Yes, there's no magic to this though.是的,这没有什么神奇之处。 In your Java AJAX handler just return a forward or redirect to the JSP page you want.在您的 Java AJAX 处理程序中,只需返回一个转发或重定向到您想要的 JSP 页面。 The response will then be available as the responseText in your AJAX callback.然后,响应将作为 AJAX 回调中的responseText可用。

You can use JSP to generate just the elements you need as a sort of incomplete HTML fragment then returns this from your server-side handler.您可以使用 JSP 生成您需要的元素作为一种不完整的 HTML 片段,然后从您的服务器端处理程序返回它。 Then in your JavaScript callback you can insert the fragment into your existing HTML like this然后在您的 JavaScript 回调中,您可以像这样将片段插入到现有的 HTML 中

element.innerHTML = resp.responseText 
//element is the parent you want to insert to 
//resp is the parameter supplied to your callback

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

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