ajax提交數據到java後臺,而且返回json格式數據前臺接收處理值

1.前臺html頁面。有一段代碼以下:javascript

帳  戶: 
 <input type="text" name="userName" id="userN" placeholder="請輸入帳戶名">
 <br />
 <br />
 <br /> 密&nbsp;&nbsp;碼:&nbsp;
 <input type="text" name="passwd" id="userP" placeholder="請輸入密碼">
 <br />
 <input type="button" value="登陸" id="userB">html

 

----------java

在頁面引入jquery庫(具體能夠去網上查)下邊是一段js代碼:jquery

<script type="text/javascript">
 $(document).ready(function() {
  $("#userB").click(function() {
   var name = $("#userN").val();
   var pawd = $("#userP").val();
   jQuery.ajax({
    type : 'POST',
    dataType : 'json',//提交方式是json,也能夠是html和textajax

//dataType:'json' 的意思是URL返回值是以JSON的格式傳過來的,而後在頁面上解析時就要採起JSON格式來展現。 json

    url : 'servlet/UserInfoAction',//提交到servlet中
    cache : false,
    data : {
     name : name,
     pawd : pawd,
    },
    success : function(data, textStatus) {
     //  請求成功時處理
     alert(data[0].name);//用這種寫法能取出後臺傳回來的json對象的屬性數組

     if (data[0]!=null) {
      alert("登陸成功!");
       var url = getRootPath()+ "/welcome.html";//獲取工程路徑 
//       var url = getRootPath() + "/servlet/showMessAction";
      location.href = url;
     }
    },
    error : function() {
     alert("帳戶密碼錯誤!");
    }
    
   });
  });
 });jsp

//這是一段獲取項目路徑的js方法url

//js獲取項目根路徑,如:http://localhost:8099/UniqueduHome 
 function getRootPath() {
  //獲取當前網址,如: http://localhost:8099/UniqueduHome/view/error/notAuthorize.jsp 
  var curWwwPath = window.document.location.href;
  //獲取主機地址以後的目錄,如: UniqueduHome/view/error/notAuthorize.jsp 
  var pathName = window.document.location.pathname;
  var pos = curWwwPath.indexOf(pathName);
  //獲取主機地址,如: http://localhost:8099 
  var localhostPaht = curWwwPath.substring(0, pos);
  //獲取帶"/"的項目名,如:/UniqueduHome 
  var projectName = pathName.substring(0,
    pathName.substr(1).indexOf('/') + 1);
  return (localhostPaht + projectName);
 } htm

</script>

 

2.java後臺

String username =request.getParameter("name");
  String password =request.getParameter("pawd");

//本身寫的方法,返回一個實體對象 

UserInfo userInfo = userInfoService.getUser(username, password);

 if (null != userInfo) {
   //向前臺輸出數據用response.getWriter().print()這種寫法

//JSONArray.fromObject(userInfo);轉爲json數組格式

//也能夠返回一個字符串,頁面是判斷data跟返回的字符串是否相等作邏輯處理

   response.getWriter().print(JSONArray.fromObject(userInfo));

} else {   response.setCharacterEncoding("UTF-8");   response.setHeader("content-type", "text/html;charset=UTF-8");   response.getWriter().println("<font color='red'>帳戶名/密碼錯誤</font>");   return;  } }

相關文章
相關標籤/搜索