从3.0之前的servlet检索FormData api的请求参数,其中不支持request.part

时间:2014-06-09 08:41:10

标签: javascript ajax jsp xmlhttprequest form-data

基本上我正在尝试将表单参数作为发布数据发送到另一个jsp并打印参数但我遇到了实现此问题的问题。下面是构造FormData实例并将其作为XMLHttpRequest的post数据发送到目标jsp的html代码。
                 

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function loadXMLDoc()
    {
    var form = new FormData();
    form.append('firstname', 'peter');
    form.append('lastname', 'parker');
    var xmlhttp;
    if (window.XMLHttpRequest)
      {
      xmlhttp=new XMLHttpRequest();
      }
    else
      {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("POST","sample.jsp",true);
    xmlhttp.send(form);
    }
    </script>
    </head>
    <body>

    <div id="myDiv"><h2>Text which will be changed on click</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>

    </body>
    </html>

目标jsp servlet代码如下所示,我尝试检索附加到FormData实例的参数。

<%
    out.println(request.getParameter("firstname"));
    out.println(request.getParameter("lastname"));
%>

但是当我尝试运行jsp时,我将打印的参数设置为null。我是ajax和客户端脚本世界的新手。那么有人可以解释我如何从FormData实例成功检索参数吗?

1 个答案:

答案 0 :(得分:1)

$( document ).ready(function() {
$( "#button_click" ).click(function(){
var form= new FormData();
    form.append('firstname', 'peter');
    form.append('lastname', 'parker');
$.ajax({
    url: 'sample.jsp',
    data: form,
    cache: false,
    contentType: "application/x-www-form-urlencoded",
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});
});
});

<div id="myDiv"><h2>Text which will be changed on click</h2></div>
 <button id="button_click" type="button">Change Content</button>

此外,您还需要上面的这些标题

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

现在请求并告诉我它是否有效

<强>更新

试试这个jsfiddle http://jsfiddle.net/Ujryx/25/

HTML

<form id="formoid" action="sample.jsp" title="" method="post">
    <div><label class="title">First Name</label><input type="text" id="firstname" name="firstname" ></div>
<div><label class="title">Name</label><input type="text" id="lastname" name="lastname" ></div>
<div><input type="submit" id="submitButton"  name="submitButton" value="Submit"></div>

JS

$("#formoid").submit(function(event) {

  event.preventDefault();

    var $form = $( this ),
      url = $form.attr( 'action' );

  var posting = $.post( url, { firstname: $('#firstname').val(), lastname: $('#lastname').val() } );


  posting.done(function( data ) {
    alert('success');
  });
});