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;  } }

相关文章
相关标签/搜索