【问题标题】:How to get more than 1 response in ajax called如何在 ajax 中获得超过 1 个响应称为
【发布时间】:2014-12-10 04:21:12
【问题描述】:

我正在从 JSP 上传文件并在 servlet 中对其进行处理并将数据返回给 JSP。

上传文件的JSP文件:

$(document).ready(function() {
    $(':file').change(function(){
        var fileObj = this.files[0];
        var form = $('#upload');
        var fd = new FormData();    

        fd.append( 'file', fileObj);
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: fd,
            processData: false,
                contentType: false,
            async: false,
        }).done(function(data){
            alert('ajax complete');
                $('#previewForm').append("<div>" + data + "</div>");
            $('#ldiv').hide();
        }).fail(function() {
            alert("error");
            $('#ldiv').hide();
        });
    }

Servlet 文件。

jsp上传的读取文件 假设上传 Excel 文件。 读取该文件数据并将该数据转换为 jsonString。 现在我想将该字符串作为 ajax 调用的响应发送

我需要返回超过 1 个值

System.out.print("test.xlsx");  //File name 
System.out.print(jsonSting); // jsonSting is variable that is data of excel file which convert in json
System.out.print("chintan");  //other parameter.

那么,当调用 ajax 时,我如何在 JSP 中处理 3 响应....?

【问题讨论】:

  • 生成json响应
  • afaik,无法使用 ajax 上传文件...

标签: java jquery ajax jsp servlets


【解决方案1】:

参考链接here 在你的jsp页面中

import org.json.simple.JSONObject;


      JSONObject obj = new JSONObject();

      obj.put("fileName", "test.xlsx");
      obj.put("jsonSting", jsonSting);
      obj.put("name", "chintan");

在你的 ajax 响应中

var json = $.parseJSON(data);

 $('#results').html('Filename name: ' + json.fileName + '<br />jsonSting: ' + json.jsonSting);

【讨论】:

    【解决方案2】:

    为什么不将响应包装成 json 样式的字符串,这样您就可以在 json 对象中处理 ajax 调用结果。 在您的情况下,您的 jsp 可以像这样响应结果 "{'fileName':'test.xlsx','jsonString':'****','chintan':'***'}"

    如果你有多个,你也可以在其中的json对象中标记为数组

    【讨论】:

      【解决方案3】:

      ajax 中的单个请求只会得到一个响应。您可以创建更多请求,提供与此相关的出色解决方案here

      您可以将额外的参数附加到 json 字符串本身并更改 JS 中的逻辑以从 excel 数据中分别提取这两个值,同时解析 json 字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 2017-06-12
        相关资源
        最近更新 更多