JSON,post使用jquery ajax返回失败

时间:2013-08-01 13:03:09

标签: jquery ajax json

我有下面的代码,在这里我想将整个表单转换为JSON并使用jquery AJAX发布它。我的问题是,它进入Servlet我可以获取request.getParameter中的值,但我仍然得到ajax失败。一旦我得到响应,我想显示返回的响应并将其显示在同一页面上。请帮我找出问题所在。我搜索了很多,但无法将其链接到正确的ans。许多人提前感谢!!

这是我的代码。 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();
  }
}

2 个答案:

答案 0 :(得分:0)

json的正确内容类型是:

response.setContentType("application/json");

尝试更改代码并重新测试。

答案 1 :(得分:0)

ajax调用将dataType设置为json,这意味着它需要返回json。但是,所有返回的都是“Hello User”。这不是json,可能导致错误。我会尝试使用html的dataType,并在Java方法中使用setContentType(“text / html”)而不是“text / json”