我有下面的代码,在这我想将整个表单转换为JSON和使用jQuery AJAX发布。我的问题是,它进入到Servlet中,我可以在request.getParameter中获取值,但我仍然得到ajax失败。一旦我收到回复,我想显示返回的回复并将其显示在同一页面上。请帮我找出错误的地方。我搜查了很多,但无法将其链接到右侧。许多提前感谢!JSON,使用jquery ajax后返回失败
在这里我的代码。 ShowHideDiv_ajax.html
$(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;
}
});
Enter your name : | |
Education : | |
而且的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();
}
}