1

我有这个问题,我昨天已经问过这个问题但我没有任何答案...... :(

我在客户端有这段代码:

 var formdata = new FormData();
    //fill fields of formdata... for example:
    var file = document.getElementById("file").files[0];
    formdata.append("file", file);
    //and others....but the problem is not here
    var xhr = new XMLHttpRequest();
    xhr.open("POST","http://127.0.0.1:8080/Commerciale",true);
    xhr.send(formdata);
    xhr.onreadystatechange = function() {

        if (xhr.readyState == 4) {
    if (xhr.status == 200) {
                   var str = xhr.responseText;
                   alert(str);
              }
         }
      });

到目前为止,这似乎是公平的。在 servlet 中,我有以下代码:

 protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException             {
   ***other code, but i think that the problem is here:
   PrintWriter ajaxWriter = response.getWriter();
   ajaxWriter.println(p.getJSON());
   ajaxWriter.flush();          
   System.out.println(p.getJSON());
   ajaxWriter.close();
 }

问题在于

 System.out.println(p.getJSON()); 

打印出我的期望,但似乎

 xhr.responseText 

不返回任何东西,实际上警报是空的。

有人可以解释我为什么吗?

4

2 回答 2

1

:) 发现这是原因后:

冲洗后不应关闭写入器。
删除行:

ajaxWriter.close();

一个有趣的相关问题 -是否应该在 HttpServletResponse.getOutputStream()/.getWriter() 上调用 .close()?

尽管没有禁止关闭编写器/流的特定文档 - 这是容器应该执行的操作,而不是应用程序。

于 2012-10-14T10:09:40.927 回答
0

您应该在 POST 请求上设置内容类型:

    var formdata = new FormData();    
    var file = document.getElementById("file").files[0];
    formdata.append("file", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST","http://127.0.0.1:8080/Commerciale",true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var str = xhr.responseText;
            alert(str);
        }
     }
  };
xhr.send(formdata);
于 2012-10-14T08:35:01.147 回答