2013-07-23 35 views
1

我正在发布一个jQuery AJAX POST到一个servlet并且数据是JSON字符串的形式。 我不确定数据是否获得发布。另外,我想通过从json对象中获取来验证登录名和密码。读取servlet中的JSON值

继承人的代码片段:

<script src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> 

    <script type="text/javascript">    
    function doajax(){ 

    var fullname=$("#fullname").val; 
    var mobileno=$("#mobileno").val; 


     $.ajax({ 
     url: 'dvsds', 
     type: 'POST', 
     dataType: 'json', 
     data:{ "mobileno":mobileno, "fullname":fullname}, 
      error:function(){ 
       alert("error occured!!!"); 
      }, 
      success:function(data){ 
       alert(data.message); 
     } 
     }); 
     } 
</script> 

我的servlet端代码:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    response.setContentType("application/json"); 
    PrintWriter out = response.getWriter(); 
    try { 
     String message=null; 

     JSONObject jObj = new JSONObject(request.getParameter("jsondata")); 
     Iterator<String> it = jObj.keys(); //gets all the keys 

     String Name=null; 
     String mobileno=null; 

     while(it.hasNext()) 
     { 
      String key = (String) it.next(); // get key 

      if(key.equals("fullname")) 
       Name = (String)jObj.get(key); 
      else if(key.equals("mobileno")) 
       mobileno=(String)jObj.get(key); 
     } 


     if(Name=="abc" && mobileno=="123") 
      message="success"; 
     else 
      message="fail"; 

     JSONObject jsonObject = new JSONObject(); 
     jsonObject.put("message", message); 
     out.println(jsonObject); 

回答

0

您不需要字符串化数据...只是把它作为一个普通的旧JavaScript对象.. 。通过指定数据类型为json ... jquery将弄清楚如何打包请求中的数据

无需在服务器端更改任何东西

所以,如果您的AJAX调用变为:

$.ajax({ 
    url: 'dvsds', 
    type: 'POST', 
    dataType: 'json', 
    data: jsondata, 
     error:function(){ 
      alert("error occured!!!"); 
     }, 
     success:function(data){ 
      alert(data.message); 
    } 
    }); 

检索它们在servlet作为

String fname = request.getParameter("fullname"); 
String mobileno = request.getParameter("mobileno"); 

我想你会需要小心区分大小写

EDITED

我看到你可以改变你的脚本如下。

<script type="text/javascript">    
function doajax(){ 

var fullname=$("#fullname").val; 
var mobileno=$("#mobileno").val; 

var postReqData = {}; // Create an empty object 
postReqData['mobileno'] = mobileno; 
postreqData['fullname'] = fullname; 


    $.ajax({ 
    url: 'dvsds', 
    type: 'POST', 
    dataType: 'json', 
    data: postReqData, 
     error:function(){ 
      alert("error occured!!!"); 
     }, 
     success:function(data){ 
      alert(data.message); 
    } 
    }); 
    } 

+0

jsshah嗨,我没有提到,但仍以其表现失败了,因为从servlet响应看重的返回。 – shanky

+0

我编辑了答案......你可以试试这个 – jsshah

0

jQuery.Ajax功能的datatype属性规定如下:

的数据类型(默认:智能猜测(XML,JSON,脚本或HTML))

类型:字符串

您期待的数据类型e服务器。

所以,你发送的不是JSON字符串。你发送的是普通的旧请求数据。

你可以在你的servlet使用得到这样的数据:

String mobileno = request.getParameter("mobileno");