简体   繁体   English

从Spring Controller返回数据到Ajax

[英]Returning data to ajax from spring controller

So I am having my add to cart for a "DVD" store button make an ajax call to my server to access the check whether there are enough DVDs in stock in the database and add it to the "cart" in the session.I feel like I have the "call" right but not too sure on how to get my spring controller to "respond".I essentially just want an object with the fields "successStatus" and "message" to be returned to the ajax to display to the user. 因此,我将要添加到“ DVD”存储按钮的购物车中,对服务器进行ajax调用,以访问数据库中是否有足够的DVD库存,并将其添加到会话中的“购物车”中。就像我拥有“调用”权限,但不太确定如何使我的spring控制器“响应”。我基本上只是希望将具有字段“ successStatus”和“ message”的对象返回给ajax以显示给用户。

My button in the html 我在HTML中的按钮

 <form method="post">
 <p>Enter quantity you would like to purchase :
<input type="number" id="quantity" name="quantity" step="any" min="1" max="${product.quantityInStock}" value="1"></input>
 </p>
<input type="submit" class="btn btn-primary"  id="addToCart"  name="button" value="Add to cart"/>
<input type="hidden" id="jsonProductId" value='${product.id}'/>
</form>

Ajax call 阿贾克斯电话

  $("#addToCart").click(function(event) {

        var data = {}
        data["productId"] = $("#jsonProductId").val();
       data["quantity"] = $("#quantity").val();

        $.ajax({
                 type: "POST",
                 contentType: "application/json",
                 url: "addToCart",
                 data: JSON.stringify(data),
                 dataType: 'json',
                 timeout: 600000,
                 success: function (data) {

                     //...
                 },
                 error: function (e) {

                     //...
                 }
        });
  event.preventDefault();

    });

Controller 调节器

  @Controller
  @Scope("session")
  public class CartController {
@Autowired
private Cart cart;
@Autowired
ProductService productService;



@RequestMapping(value="/addToCart", method= RequestMethod.POST)
public String searchResults(@RequestBody AddToCartPojo addToCartPojo) {
   //do something
}

@RequestMapping(value="/cart", method= RequestMethod.GET)
public String searchResults(Model model) {
model.addAttribute("cartLines",cart.getLines());
model.addAttribute("cartTotalPrice",cart.getTotalPrice());
    return "cart";
}

AddToCartPojo AddToCartPojo

public class AddToCartPojo {
private long productId;
private int quantity;

public long getProductId() {
    return productId;
}

public void setProductId(long productId) {
    this.productId = productId;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}
}

Just change your controller a bit 稍微改变一下控制器

@RestController
@Scope("session")
public class CartController {

    @Autowired
    private Cart cart;
    @Autowired
    ProductService productService;

    @RequestMapping(value="/addToCart", method= RequestMethod.POST)
    public String searchResults(@RequestBody AddToCartPojo addToCartPojo) {
       //do something

       String responseMessage = "success";
       return responseMessage;
    }
}

I added @RestController annotation instead of @Controller , which implicitly adds @ResponseBody to every method in this class. 我添加了@RestController注释而不是@Controller ,这将@ResponseBody隐式添加到@ResponseBody中的每个方法。

@Response Body - Annotation that indicates a method return value should be bound to the web response body. @Response正文 -指示方法返回值的注释应绑定到Web响应正文。 Supported for annotated handler methods in Servlet environments. 在Servlet环境中支持带注释的处理程序方法。

No need to send status separately. 无需单独发送状态。 Instead HTTP status could be used. 而是可以使用HTTP状态。 If you have 200 then success. 如果您有200,则成功。

If you use @Controller without @ResponseBody , after requests are processed by the CartController and the response is returned to the DispatcherServlet with logical view name (In your example it is "cart"). 如果您使用@Controller没有@ResponseBody ,请求由处理后CartController和响应返回到与逻辑视图名称DispatcherServlet的(在你的榜样是“车”)。 Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked. 然后返回到视图解析器,根据您的配置准备好视图,然后决定要调用哪个配置(JSP,Velocity,PDF等)。 (For example, use cart.jsp page). (例如,使用cart.jsp页面)。

@ResponseBody - Annotation that indicates a method return value should be bound to the web response body. @ResponseBody-表示方法返回值的注释应绑定到Web响应正文。 Supported for annotated handler methods in Servlet environments. 在Servlet环境中支持带注释的处理程序方法。

So if you annotate method with @ResponseBody response will be returned to the browser and will be available in success: function(data) as data param. 因此,如果您使用@ResponseBody注释方法,响应将返回到浏览器并success: function(data)作为数据参数。

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

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