我有以下代码,在此我想将整个表单转换为 JSON 并使用 jquery AJAX 发布它。我的问题是,它进入了 Servlet,我可以在 request.getParameter 中获取值,但我仍然遇到 ajax 失败。一旦我得到响应,我想显示返回的响应并将其显示在同一页面上。请帮我找出问题所在。我已经搜索了很多,但无法将其链接到正确的答案。非常感谢提前!
这是我的代码。ShowHideDiv_ajax.html
<script>
$(document).ready(function() {
$('#form_submit').click(function (event) {
event.preventDefault();
var form = $("#myform");
var json = ConvertFormToJSON(form);
$("#results").text(JSON.stringify(json) );
$.ajax({
url: 'AjaxServlet',
type: 'POST',
dataType: 'json',
cache: false,
//contentType: 'application/json; charset=utf-8',
data: json,
success: function( response ) {
//I want to use this response to be displayed on the same page.
alert('success');
},
error: function() { // if error occured
alert('fail:');
}
});
return false;
});
function ConvertFormToJSON(form){
var array = form.serializeArray();
var json = {};
$.each(array, function() {
//alert('this.name='+this.name+'this.value='+this.value);
if (json[this.name] !== undefined) {
if (!json[this.name].push) {
json[this.name] = [json[this.name]];
}
jsono[this.name].push(this.value || '');
} else {
json[this.name] = this.value || '';
}
});
return json;
}
});
</script>
<style>
</style>
</head>
<body>
<form class="ajax_form" id="myform" name="myform" method="post" action="AjaxServlet" >
<table>
<tr>
<td colspan="2"><div id="error" class="error"></div></td>
</tr>
<tr>
<td>Enter your name : </td>
<td> <input type="text" id="name" name="firstname"><br/></td>
</tr>
<tr>
<td>Education : </td>
<td> <input type="text" id="education" name="edu"><br/></td>
</tr>
<tr>
<td colspan="2"><div id="info" class="success"></div></td>
</tr>
</table>
</form>
<p><tt id="results"></tt></p>
<p><tt id="results1"></tt></p>
<input class="ajax_button" type="submit" value="Submit" id="form_submit" name="form_submit">
</body>
和 Servelt AjaxServlet.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("in post ajaxservlet");
try {
String fn, ed=null;
fn = request.getParameter("firstname");
ed = request.getParameter("edu");
System.out.println("receieved data:"+fn+ed);
if(request.getParameter("firstname").toString()!=null){
fn="Hello User";
}
PrintWriter out = response.getWriter();
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
out.write(fn);
out.close();
System.out.println("data posted");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}