有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

在下面的代码中,我通过submit提交表单,但来自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) 个答案

  1. # 1 楼答案

    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);
        });
      });
    });
    

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

    上传文件本身就是另一种动物……)