serialize()与serializeArray()

1.了解serialize()与serializeArray()

serialize()序列化表单元素,用于ajax请求,

serializeArray()序列化表单元素,类似于serialize,但是返回的是json格式的对象,注意是对象返回的不是字符串,也可以用于ajax请求

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FormJson</title>
<script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
<style>
</style>
<script type="text/javascript">
    $(document).ready(function() {
        $("#get").click(function() {
            data1 = $("#myForm :text").serializeArray();
            data2 = $("#myForm").serialize();
            console.log(data1);
            console.log(JSON.stringify(data1))
            console.log(data2);
            $.each(data1, function(i, field) {
                $("#results").append(field.name + ":" + field.value + " ");
            });
        });
    });
</script>
</head>
<body>
    <form id="myForm" action="">
        name: <input type="text" name="FirstName" value="Bill" /><br /> sex:
        <input type="text" name="sex" value="man" /><br /> 
        <select name="education">
            <option value="本科">本科</option>
            <option value="研究生">研究生</option>
        </select>
    </form>

    <button id="get">序列化表单值</button>
    <div id="results"></div>
</body>
</html>

PS:

$("form").serialize(); //这一句是获取网页内所有表单的值
$("form#myForm");//获取form中的myForm这个一个表单

$("#myForm:text");//获取myForm表单中为输入框的选项

$("#myForm:select");//获取myForm表单中为下拉框的选项

json对象转字符串:主流浏览器都支持JSON.stringify()

 2.利用serialize简单完成登陆

这部分为自己原创,也顺便应付下Http老师布置的登陆任务,html页面代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FormJson</title>
<script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
<style>
</style>
<script type="text/javascript">
    $(function(){
        $("#submit").click(function() {
            data1 = $("#myForm").serializeArray();
            //console.log(data1);
            data2 = JSON.stringify(data1);
            //console.log(data2);
            data3 = $("#myForm").serialize();
            //console.log(data3);
            var str ="";
            jQuery.ajax({
                type: 'POST',    //请求方式
                url:"myHandle.jsp?flags=login",
                dataType: "json",    //预期服务器返回的数据类型
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",    //返回给服务器时候的字符编码
                data: data3,    //发送到服务器上的数据,测试了一下传data2的话是不行的,data1与data3可以
                success: function (data) {   
                    console.log(data);
                    if (data.statusCode == 200){    //修改成功的状态码为200
                        str+='<span>恭喜您登录成功,您的姓名是'+data.name+'</span>';
                        str+='<br/><span>您的密码是'+data.password+'</span>';
                        $("#result").html(str);
                    }else if(data.statusCode == 500){
                        $("#result").html("");
                        $("#loginInf").html("用户名或者密码输入错误!"+'<br/>');
                    }
                },
                error: function (data) {
                    
                }
            });
         });        
    })
</script>
</head>
<body>
    <form id="myForm">
        <span id="loginInf"></span>
        姓名: <input type="text" name="name" /><br /> 
        密码: <input type="password" name="password" /><br />
    </form>
    <button id="submit">登陆</button>
    <div id="result"></div>
</body>
</html>
<%@page contentType="text/html; charset=utf-8" import="business.jqueryForm,java.util.Enumeration,java.io.*,java.net.URLEncoder,java.util.HashMap"%> 
<jsp:useBean id="myHandle" class="business.jqueryForm" scope="page"></jsp:useBean>
<jsp:setProperty property="*" name="myHandle"/>
<%
    //测试使用,打印参数
     Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
        System.out.println(e.nextElement());
    } 
    System.out.println("flags:" + myHandle.getFlags());
    //获取处理结果
    String returnStr = myHandle.getData(request, response);
    System.out.println("[DEBUG][returnStr]" + returnStr);
    //向前台输出结果
    out.println(returnStr);
%>

然后dao层用到了如c3p0连接池,数据库连接工具类,dbutils工具简便一下开发,顺便在温习一下

package business;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.json.JSONObject;

import sun.org.mozilla.javascript.internal.ast.NewExpression;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class jqueryForm {

    /*
     * 统一获取数据的入口
     */
    public String getData(HttpServletRequest req, HttpServletResponse resp)
            throws SQLException {
        if ("login".equals(flags))
            return Login();

        return "";
    }

    /*
     * 判断是否登录成功
     */
    private String Login() throws SQLException {
        // System.out.println(name+"...."+password);
        JSONObject jsonObject = new JSONObject();
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from http_login where name='" + name + "' and password='" + password + "'";
        jqueryForm query = qr.query(sql, new BeanHandler<jqueryForm>(jqueryForm.class));
        if (query != null) {
            jsonObject.put("statusCode", 200);
            jsonObject.put("name", query.getName());
            jsonObject.put("password", query.getPassword());
        } else {
            jsonObject.put("statusCode", 500);
        }
        return jsonObject.toString();
    }

    // 实体bean参数以及getter/setter
    private String name;
    private String password;
    private String flags;

    public String getFlags() {
        return flags;
    }

    public void setFlags(String flags) {
        this.flags = flags;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

运行效果大概是这样的,样式就没管了

自己之前看黑马机构的视频,使用servlet+jsp完成,把用户的信息存到cookie中了,然后再jsp页面用el表达式和jstl标签进行回显登录信息的状态!

当然了,实现方式数不胜数, 比如还可以用ajax+servlet的方式实现,servlet的代码我也写了写,上个学期自学的javaweb,顺便在温习一下。

发现自己老是忘记servlet生命周期,在改动了web.xml中的信息后,总是不记得重新将项目发布到服务器中去,有次还闹笑话找错找了半个小时

package business;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.json.JSONObject;

@WebServlet("/jqueryForm")
public class jqueryFormServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取表单数据
        Map<String, String[]> map = request.getParameterMap();
        jqueryForm form = new jqueryForm();
        //一一对应set进去(需要引入beanutils的jar包),减少一个一个的request.getParameter("")与set进去了
        //注意前台name字段要与表字段一致,功能类似于jsp的usebean,setbean标签
        try {
            BeanUtils.populate(form,map);            
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //这里就不采用MVC模式了,懒
        JSONObject jsonObject = new JSONObject();
        try {
            String loginInfo = Login(form.getName(),form.getPassword());
            jsonObject.put("statusCode", loginInfo);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(jsonObject.toString());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /*
     * 判断是否登录成功
     */
    private String Login(String name,String password) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(*) from http_login where name='" + name + "' and password='" + password + "'";
        Long query = (Long) qr.query(sql, new ScalarHandler());
        if (query > 0) {
            return "200";
        } else {
            return "500";
        }
    }
}

 

posted @ 2019-04-17 00:02  曾聪聪  阅读(2256)  评论(0编辑  收藏  举报