无法从JS表单调用servlet

无法从JS表单调用servlet

本文介绍了无法从JS表单调用servlet doPost方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从动态生成的Javascript形式调用servlet doPost方法时遇到问题.

I'm facing an issue in calling a servlet doPost method from my dynamically generated Javascript form.

var form = document.createElement("form");

    form.setAttribute("action", 'cisco-fetch-devices');
    form.setAttribute("method", 'POST');

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");

    hiddenField.setAttribute("name", 'hiddeninputfield');
            hiddenField.setAttribute("value", data);

    form.appendChild(hiddenField);
    document.body.appendChild(form);

    form.submit();

但是我能够从jquery ajax调用中调用相同的servlet"cisco-fetch-devices":

However I'm able to call the same servlet ''cisco-fetch-devices' from a jquery ajax call:

    $.post("cisco-fetch-devices", { orderId : data},
    function(data) {
    alert("Data Loaded: " + data);
    });

JS动态表单提交正在生成找不到文件错误"

The JS dynamic form submit is generating a 'File not found error'

这是我的doPost方法:

Here is my doPost method:

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {



            response.setContentType("text/csv");
            response.setHeader ("Content-Disposition", "attachment;filename=\"tableincsv.csv\"");

             String orderId = request.getParameter("orderId").toString();
             java.io.PrintWriter out = response.getWriter();
             out.print("TEST DAta");


        }

能否让我知道JS的传统POST调用中可能出现的问题?

Could you please let me know what might be the issue in the traditional POST call of JS?

谢谢,阿迪亚(Aditya)

Thanks,Aditya

推荐答案

您要发送的数据将不相同-您的hiddeninputfield字段应命名为orderId,并使用订单ID进行初始化.另外,您可以解析hiddeninputfield请求参数,但这似乎很愚蠢.

The data you're sending won't be the same--your hiddeninputfield field should be named orderId, and be initialized with the order ID. Alternatively, you could parse the hiddeninputfield request parameter, but that seems kind of silly.

jQuery调用正确发送了orderId表单值.

The jQuery call correctly sends an orderId form value.

通过查看servlet中的orderIdnull,和/或查看浏览器发送的实际请求以查看正在发送的参数以及发送方式,调试起来非常简单.

It would have been very simple to debug this by seeing that orderId was null in the servlet, and/or by looking at the actual request sent by the browser to see what parameters were being sent, and how.

这篇关于无法从JS表单调用servlet doPost方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:34