如何在同一页面上而不是在新页面上获得响应

时间:2014-05-06 15:20:43

标签: java javascript

在下面的代码中,我通过提交但是从javascript提交表单,响应将转到其他页面,是否有任何方法可以在同一页面上获得该响应,以便我可以使用jquery将该内容替换到某处。

//控制器端代码

 @RequestMapping(value = "upload", method=RequestMethod.POST) 
    public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response,
    @RequestPart("dataFile") MultipartFile file
    ){ if(file!=null){
    //code to upload file and will return 1
            return "1";
        }
        return "0";//otherwise it will return 0
    }

以下是html侧码

<html>

<script language="Javascript">
function fileUpload(form) {  
    // Submit the form...
    form.submit();
// here if i get that response then i'll be able to put that content somewhere else via jQuery. i dont want response directed on url/upload.

}
</script>

//html code 
<!-- index.php could be any script server-side for receive uploads. -->
<form target="upload_iframe" method="post" action="upload" enctype="multipart/form-data" encoding="multipart/form-data">
<input type="file" name="dataFile" id="dataFile" /></br>
<input type="button" value="upload"
        onClick="fileUpload(this.form); return false;" >
<div id="uploadShow"></div>
</form>

</html>

1 个答案:

答案 0 :(得分:0)

jQuery的ajax函数应该可以解决这个问题......

HTML

<div id="content">
  <form id="myform">
  <input type="text" name="myfield" />
  <input type="submit" value="go" />
  </form>
</div>

JQuery的

jQuery(document).ready(function($){
  $('#myform').on('submit',function(e){
    //prevent form redirection, natural submit...
    e.preventDefault();
    //post to your php handler...
    $.post(HTTP_PATH_TO_PHPFILE,$(this).serialize(),function(resp){
      // replace content with response..
      $('#content).html(resp);
    });
  });
});

注意:这是对一般问题的回应...... “在下面的代码中,我通过提交提交表单,但是从javascript提交表单并且响应将转到其他页面,是否有任何方法可以在同一页面上获得该响应,以便我可以使用jquery将该内容替换到某个地方。”

执行文件上传本身就是另一种动物.. :)

相关问题