【问题标题】:Can not call Spring controller when use ajax使用ajax时无法调用Spring控制器
【发布时间】:2017-10-24 04:54:36
【问题描述】:

在 Spring 中使用 ajax 时遇到问题

当我从选择框中选择区域或在屏幕上输入商店名称时,我想要过滤列表结果,所以我的想法是使用 Ajax 来解决这个问题。但是 Ajax 不能调用 $.ajax 的 url 属性中的特定控制器

以下是我的文件:

  1. JSP:

应用商店搜索的 CSS id

<form:form modelAttribute="appliedStoreInput" id="appliedStoreSearch">

    <form:select path="regionId" cssClass="form-control">
        <form:option value="" label="Toàn quốc"></form:option>
        <form:options items="${listRegions}" />
    </form:select>

    <input type="email" class="form-control"placeholder="Tìm kiếm cửa hàng" name="storeNameInp" />
    <div class="input-icon">
        <i class="fa fa-search"></i>
    </div>

</form:form>
  1. 阿贾克斯

    $(document).on('change','#appliedStoreSearch',function(e){
     var input = $("#appliedStoreSearch").serialize();
     e.preventDefault();
     $.ajax({
        url:"/promotions_controller/search_applied_store_ajax",
        method:"POST",
        contentType : "application/json;",
        dataType:"json",
        data:input,
        success: function(data){
        }
    });
    e.preventDefault();
    });
    
  2. 控制器:

    @RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces="application/json" )
    public @ResponseBody List<AppliedStoreDto> searchAppliedStoreAjax( @ModelAttribute("appliedStoreInput")AppliedStoreInputDto appliedStoreinput){
    
        System.out.println("in ra 1 so thu gi go");
    
        List<AppliedStoreDto> listAppliedStore = null;
    
        appliedStoreinput.setCompanyId(7);
    
        try {
    
         // get list applied store
         listAppliedStore = promotionLogic.findAllAppliedStore(appliedStoreinput);
    
        } catch (Exception e) {
    
         logger.error(e.getMessage());
    
        }
    
      return listAppliedStore;
    }
    

我已经调试了 Javascript,然后我从表单中检索了数据,但 Ajax 仍然无法调用 Spring 控制器 (/promotions_controller/search_applied_store_ajax)。控制台中没有显示任何内容

请帮帮我,tks all!!!!

【问题讨论】:

  • akuma8,你能帮帮我吗?
  • 你能添加你的控制器映射吗?在这里,您仅添加了处理程序方法。如果请求真的被发送,还要检查。

标签: ajax spring url model-view-controller controller


【解决方案1】:

肖恩的回答基本正确。只需添加确切的细节。函数声明应如下所示

@RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces = { MediaType.APPLICATION_JSON_VALUE}, consumes = {
        MediaType.APPLICATION_JSON_VALUE} )

public @ResponseBody List searchAppliedStoreAjax(@RequestBody AppliedStoreInputDto appliedStoreinput){

【讨论】:

    【解决方案2】:

    鉴于您的 ajax 调用的 contentType 为“application/json;”我会考虑将 consumes = "application/json" 添加到您的 RequestMapping 并将 ModelAttribute 交换为 RequestBody

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2021-05-22
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多