gpt4 book ai didi

Spring Controller - 发送 html 作为响应

转载 作者:行者123 更新时间:2023-12-03 11:28:48 25 4
gpt4 key购买 nike

我有一个加载的 jsp 页面,其中包含产品和针对它的 addtocart 链接。我试图在同一页面的 div 中显示购物车。我想发送 html 作为响应。这就是我所做的。它只返回字符串 <div>output</div> .有人可以告诉我我应该怎么做。

Controller

    @RequestMapping(value="/addtocart{id}",  produces = "text/plain;charset=UTF-8")
@ResponseBody
public String addToCart(@PathVariable("id") int id, @ModelAttribute("cart") Cart cart,Model model)
{
Product product = productService.getProductById(id);
if (product != null) {
CartLine line = new CartLine();
line.setProduct(product);
line.setQuantity(1);
productService.updateProduct(product);
}
return "<div>output</div>";
}

JSP
<td><a id="demo4" href="addtocart${product.id}">Add To Cart</a> </td>

$('#demo4').click(function() {

$.ajax({
url : '/addtocart{id}',
dataType: 'json',
contentType: "text/html",
type : 'GET',
data :{id:id},
success : function(response) {
$('#output').html(response);
}
});
});

<div id="output" style="display:none">
<h2>Cart Content(s):</h2>
</div>

最佳答案

我也喜欢使用 View 的方法,即使在 ajax 调用中也可以分开页面。尽管如此,您要问的是可能的,只需更改您的 produces = "text/plain;charset=UTF-8"生产

produces = "text/html;charset=UTF-8"

还有许多其他方面似乎是错误的,与 Spring MVC 无关,因此即使对生产进行了更正,您仍然需要做一些更正才能获得预期的结果。
  • 我认为您根本没有发送 ajax 调用。您很可能正在执行完整的浏览器重定向。第一次阅读时,我很困惑“text/plain”与“text/html”在 ajax 响应中的区别,但现在我相信您实际上是通过浏览器重定向。改这个 <a id="demo4" href="addtocart${product.id}">Add To Cart</a>变成这样的 <a id="demo4" href="#">Add To Cart</a>并添加 return false到你的函数结束。这将执行该函数,返回将确保没有跟踪链接
  • 当您这样做时,您也会注意到 ajax 调用的一些问题;首先,url : '/addtocart{id}'应该是 url : '/addtocart${product.id}
  • 在完整函数中捕获您的响应未成功,并将输出作为 response.responseText,响应将正常返回,但浏览器将尝试将其解析为 json 并失败。
  • 你的 div 将保持不可见,你应该添加一些 js 来切换
  • 一个 Spring MVC 问题,您的 Cart bean 似乎也有一个名为 id 的属性。因此,您的 id 路径变量应该重命名,否则将被忽略

  • 如果不是完全的话,这将比工作更接近
    <a id="demo4" href="#">Add To Cart</a>

    <div id="output"></div>
    <script>

    $('#demo4').click(function() {

    $.ajax({
    url : '/addtocart${product.id}',
    dataType: 'json',
    contentType: "text/html",
    type : 'GET',
    data :{id:4},
    complete: function(response) {
    $('#output').html(response.responseText);
    }
    });
    return false;
    });
    </script>

    重命名 PathVariable
    @RequestMapping(value="/addtocart{productId}",  produces = "text/plain;charset=UTF-8")
    public String addToCart(@PathVariable("productId") int productId, @ModelAttribute("cart") Cart cart,Model model)

    关于Spring Controller - 发送 html 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26607332/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com