【问题标题】:Back to same view after Ajax request and Spring response在 Ajax 请求和 Spring 响应之后返回相同的视图
【发布时间】:2017-04-05 03:08:49
【问题描述】:

我将数据托盘保存到服务器并使用添加的数据刷新视图。向服务器发送多部分请求后。在服务器部分,可以将数据保存到基础和返回 json 对象。问题是,无法刷新相同的视图,服务器通过操作方法发送 json 响应。我可以重定向,但这没有选择。不会出现错误。我发现类似帖子在触发器 click() 函数和 Ajax 选项 override:true 中使用 e.preventDefault() 很有吸引力,但这无济于事。怎么绕道呢?

Template code .  

        <form  action="/video/addCasePost" id="formAddPoster" method="post" enctype="multipart/form-data" >

                    <div class="form-group">    
                  <label for="caseTitle" class="col-sm-2 control-label">title</label>
                <div class="col-sm-10">
                <input type="text" class="form-control input-sm" id="caseTitle" name="caseTitle" value="" placeholder=“add” title here …  />
                </div>
                  </div>
<div class="form-group">

                    <label for="casePosterLoad" class="col-sm-2 control-label">post</label>
                    <div class="col-sm-10  ">
                           <input type="file" name="file" required id="fileLoader" /> 
                    </div>
                      </div>
          <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input type="hidden" class="form-control input-sm" id="postId" name="postId" value="{{item.postId}}" />
                        <button type="submit" id="btnSaveCasePost" class="btn btn-default"></button>  
                      <!-- save content --> 
                    </div>
                  </div> 



function casePostUpload()
    {
var myForm = form.find('formAddPoster');
    myData = new FormData();
    myData.append('multipart',  myForm);

       $
          .ajax({

              url : "/video/addCasePost",
              data : myForm,
              type : 'POST',
              headers: {'Content-Type': undefined},
              enctype: 'multipart/form-data',
              processData: false, 
              contentType:false,
              success : function(data, textStatus, jqXHR){


                  $('#casePost').prepend('<br/>Poster: '+data.casePoster+' ::  title '+data.caseTitle+' at '+data.timestampAsStr+'<br/></td></tr>');


            },
              error : function(result){
                  //...;

                alert('add contnt error: ' + errorThrown);
              }
          });
    }






Spring MVC controller method


    @RequestMapping(value = "/video/addCasePost",   method = RequestMethod.POST )
 public @ResponseBody CasePost addcasepost( @RequestPart("caseTitle") String caseTitleString, 
    @RequestPart("file") MultipartFile file, HttpServletRequest request, Model model, @ModelAttribute("currentuser") User currentuser) throws Exception {
   CasePost jsResponse = new CasePost();


    String filePath = new String();
     //save file to directory 
    if (!file.isEmpty()) {
        try {
            String uploadsDir = “/fd/ct/images/";
            String realPathtoUploads =  request.getServletContext().getRealPath(uploadsDir);
            if(! new File(realPathtoUploads).exists())
              {
                new File(realPathtoUploads).mkdir();
              }


            String orgName = file.getOriginalFilename();
             filePath = realPathtoUploads + orgName;

            File dest = new File(filePath);
            file.transferTo(dest);

            }catch (Exception e) {
                log.error(e);
            }

    }   

    try {
        if (caseTitleString != null) {



            jsResponse.setCaseTitle(caseTitleString);

            jsResponse.setCasePoster(filePath);

            jsResponse = graphStoryInterface.getCasePostInterface().add(jsResponse, currentuser);

        }
    }
    catch (Exception e) {
        log.error(e);
    }

 return jsResponse;


}

【问题讨论】:

  • 通过“刷新视图”,您的意思是向现有元素添加一些 HTML 吗?您的 ajax 调用显示您向 #casePost 元素添加了一些内容,但这似乎不存在于您的 HTML 代码中。
  • 您要么使用表单操作,要么单独使用 ajax。由于您使用的是 ajax,您可能会摆脱 formAction,然后处理响应数据。无需重新加载/重定向。
  • Winter Soldier 对于发送请求,只使用了 ajax。
  • dhc 这个 HTML 代码存在,但我没有在帖子中添加。我认为这与本案无关。

标签: java jquery json ajax spring


【解决方案1】:

form data 在您的情况下未通过。

修改了表单数据并修剪了不需要的表单操作。

function casePostUpload() {
 myData = new FormData($('#formAddPoster'));
 myData.append('multipart',  myForm);
 $.ajax({
      url : "/video/addCasePost",
      data : myData,
      type : 'POST',
      headers: {'Content-Type': undefined},
      enctype: 'multipart/form-data',
      processData: false, 
      contentType:false,
      success : function(data, textStatus, jqXHR){
          $('#casePost').prepend('<br/>Poster: '+data.casePoster+' ::  title '+data.caseTitle+' at '+data.timestampAsStr+'<br/></td></tr>');
    },
      error : function(result){
          //...;

        alert('add contnt error: ' + errorThrown);
      }
  });
}

<form id="formAddPoster" enctype="multipart/form-data">
  <div class="form-group">
    <label for="caseTitle" class="col-sm-2 control-label">title</label>
    <div class="col-sm-10">
      <input type="text" class="form-control input-sm" id="caseTitle" name="caseTitle" value="" placeholder=“add” title here … />
    </div>
  </div>
  <div class="form-group">

    <label for="casePosterLoad" class="col-sm-2 control-label">post</label>
    <div class="col-sm-10  ">
      <input type="file" name="file" required id="fileLoader" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <input type="hidden" class="form-control input-sm" id="postId" name="postId" value="{{item.postId}}" />
      <button type="submit" id="btnSaveCasePost" class="btn btn-default"></button>
      <!-- save content -->
    </div>
  </div>

【讨论】:

  • 使用 FormData 对象一切正常。 Firebag 显示 200 正常。内容类型多部分/表单数据;边界=---------------158gsd546464546564。我可以沙文件和json。
  • 您的问题已经解决了吗?或者您现在卡在哪里了?
  • 发布之前的某个时间点。通过 Ajax 方法 /video/addCasePost 回复 url
  • 我可以通过这个堆栈。问题出在 Jquery 版本上。旧版本无法识别某些方法。 Thx Winter Soldier,您的回答引出了一些想法。)
  • 很高兴听到这个消息。如果解决了,请您接受答案,这样其他人就不必花时间在这上面了。谢谢
猜你喜欢
  • 2019-05-07
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多