jquery ajax 返回失败,JSON,使用jquery ajax后返回失败

我有下面的代码,在这我想将整个表单转换为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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值