如何设置XMLHttpRequest的响应

时间:2018-03-09 21:00:54

标签: servlets xmlhttprequest

所以我有这个函数将文档发送到一个servlet,它将它存储在我的数据库中,一切正常:

function submitAttachment(formName, formId, fieldName) {
      var formData = new FormData();
      var fileName = "";
      var files = document.getElementById(fieldName + "Document").files;

      formData.append('formName', formName);
      formData.append('formId', formId);
      formData.append('fieldName', fieldName);

      for (var i = 0; i < files.length; i++) {
          var file = files[i];
          formData.append('file', file, file.name);
          fileName = file.name;
      }

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'saveattachment', true);

      xhr.onload = function() {
          if (xhr.status === 200) { // Success
            var idDoc = xhr.responseText;
            setLinkHtml(fieldName, fileName, idDoc);
            $("#" + fieldName + "IdDocument").val(idDoc);
          }
      };

      xhr.send(formData);
}

只是,我得到的答案(来自xhr.responseText)是\ u0017。

我的servlet看起来大致如下:

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        response.setContentType("text/html; charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       request.setCharacterEncoding("UTF-8");
       PrintWriter out = response.getWriter();

        //DoStuff

        out.write(doc.getIdDocument());
    }


    //Process the HTTP Post request
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        doGet(request,response);
    }

我想要的只是返回一个号码,我做错了什么?

1 个答案:

答案 0 :(得分:0)

终于找到了! 如果有人想知道,结果返回一个数字作为某种返回代码。所以我需要做的就是添加+&#34;&#34; 所以out.write(doc.getIdDocument() + "")并且它有效!