【问题标题】:XmlHttpRequest level 2 : Response returns nothingXmlHttpRequest 级别 2:响应不返回任何内容
【发布时间】:2012-10-04 12:42:09
【问题描述】:

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

我在客户端有这段代码:

 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 

什么都不返回,其实alert是空的。

谁能解释一下为什么?

【问题讨论】:

  • 你用哪个浏览器试过这个?
  • 尽量不要关闭编写器(这应该不是问题 - 但你也不需要它)
  • 现在可以了!!!谢谢!如果您写下问题的答案,我会注意到您的答案是正确的。 :)

标签: java httpresponse xmlhttprequest-level2


【解决方案1】:

您应该在 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);

【讨论】:

  • 通过xhr.getResponseHeader检查HTTP响应,进行调试
  • 如果我更改内容类型,它会给我这个错误:错误:请求不包含 multipart/form-data 或 multipart/mixed 流,内容类型标头是 application/x-www -form-urlencoded 其实这个 content-type 对级别 1 的 XmlHttpRequest 来说是可以的..
【解决方案2】:

:) 发现是这个原因后:

刷新后不应关闭写入器。
删除行:

ajaxWriter.close();

一个有趣的相关问题 - Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

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

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2022-01-14
    • 2020-08-16
    相关资源
    最近更新 更多