JQueryjquery极简教程Java开发知识点

jQuery - AJAX、mysql的优化

2017-05-03  本文已影响55人  奋斗的老王

一)jQuery常用AJAX-API

目的:简化客户端与服务端进行局部刷新的异步通讯

1)取得服务端当前时间

    <script type="text/javascript">
        $(":button").click(function(){
            var url = "${pageContext.request.contextPath}/loadTimeRequest?time"+new Date().getTime();
            var sendData = null;
            $.load(url,sendData,function(a,b,ajax){
                var jsonJAVA = ajax.responseText;
                var jsonJS = eval("("+jsonJAVA+")");
                var strTime = jsonJS.strTime;
                $("span:first").html(strTime).css("color","red");
                $("span:last").html(strTime).css("color","blue");
            });
            //$("span").load(url);
        });
    </script>

2)检查注册用户名和密码是否存在

3)jQuery对象.serialize()

    <script type="text/javascript">
        //定位按钮,同时添加单击事件
        $(":button").click(function(){
            //获取用户名和密码
            var username = $(":text:first").val();
            var password = $(":text:last").val();
            //去空格
            username = $.trim(username);
            password = $.trim(password);
            //异步发送到服务端
            var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
            /*手工书写JSON文本
            var sendData = {
                "user.username":username,
                "user.password":password
            };
            */
            /*工具生成JSON文本*/
            var sendData = $("form").serialize();
            $.post(url,sendData,function(backData,textStatus,ajax){
                //backData是一个JSON文本/对象,你得通过.号访问其属性值
                var tip = backData.tip;
                //创建img节点
                var $img = $("![](" + tip + ")")
                //清空span节点中的内容
                $("span").text("");
                //将img节点添加到span节点中
                $("span").append( $img );
            });
        });
    </script>
public class RegisterAction extends ActionSupport{
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    /**
     * 检查注册用户名和密码是否存在
     */
    public String checkMethod() throws Exception {
        tip = "images/MsgSent.gif";
        if("帅帅".equals(user.getUsername()) && "123".equals(user.getPassword())){
            tip = "images/MsgError.gif";
        }
        return "ok";
    }
    private String tip;
    public String getTip() {
        return tip;
    }
    /**
     * var backData = {
     *                  "tip":"images/MsgError.gif"
     *                }
     */
}

4)jQuery解析XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <city>广州</city>
    <city>中山</city>
    <city>深圳</city>
    <city>佛山</city>
    <city>珠海</city>
</root>
<script type="text/javascript">
        $(":button").click(function(){
            var url = "${pageContext.request.contextPath}/03_city.xml";
            var sendData = null;
            $.get(url,sendData,function(backData,textStatus,ajax){
                /*
                //将xml文件转成jquery对象,目的是用jquery api解析xml文件
                var $xml = $(backData);
                var $city = $xml.find("city");
                $city.each(function(){
                    //获取每一个city节点
                    var city = $(this).text();
                    alert(city);
                });
                */
                var xml = ajax.responseXML;
                var $xml = $(xml);
                var $city = $xml.find("city");
                $city.each(function(){
                    //获取每一个city节点
                    var city = $(this).text();
                    alert(city);
                });
            });
        });
    </script>

5)省份-城市,基于jQuery的AJAX二级联动,用Struts2整合AJAX【非数据库版】

    <select id="province">
        <option>选择省份</option>
        <option>广东</option>
        <option>湖南</option>
    </select>
    <select id="city">
        <option>选择城市</option>
    </select>
<script type="text/javascript">
        $("#province").change(function(){
            //删除原城市下拉框中的内容,除第一项外
            $("#city option:gt(0)").remove();
            var province = $("#province option:selected").text();
            if("选择省份" != province){
                $.ajax({
                    "type":"POST",
                    "url":"${pageContext.request.contextPath}/findCityByProvince?time="+new Date().getTime(),
                    "sendData":{"province":province},
                    "success":function(backData,textStatus,ajax){
                        //js对象
                        var city = backData.cityList;
                        //jquery对象
                        var $city = $(city);
                        //each()
                        $city.each(function(){
                            //this表示每个城市
                            var $option = $("<option>" + this + "</option>");
                            $("#city").append( $option );
                        });
                    }
                });
            }
        });
    </script>
public class ProvinceCityAction extends ActionSupport{
    private String province;//广东
    public void setProvince(String province) {
        this.province = province;
    }
    public String findCityByProvince() throws Exception {
        cityList = new ArrayList<String>();
        if("广东".equals(province)){
            cityList.add("湛江");
            cityList.add("汕头");
        }else if("湖南".equals(province)){
            cityList.add("邵阳");
            cityList.add("浏阳");
        }
        return "ok";
    }
    private List<String> cityList;
    public List<String> getCityList() {
        return cityList;
    }
    /**
     * var backData = {
     *                   "cityList":["邵阳","浏阳"]
     *                }
     */
}
<struts>
   <package name="timePackage" extends="json-default" namespace="/">
        <global-results>
            <result name="ok" type="json"/>
        </global-results>

        <!-- 获取服务端时间 -->
        <action 
            name="loadTimeRequest" 
            class="cn.itcast.javaee.js.time.TimeAction" 
            method="loadTimeMethod"/>

        <!-- 检查用户名和密码是否存在 -->
        <action 
            name="checkRequest" 
            class="cn.itcast.javaee.js.register.RegisterAction" 
            method="checkMethod"/>
            
        <!-- 根据省份查询城市 -->   
        <action 
            name="findCityByProvince" 
            class="cn.itcast.javaee.js.provincecity.ProvinceCityAction" 
            method="findCityByProvince"/>
   </package>
</struts>

二)掌握Java调用Oracle过程与函数

--定义过程
create or replace procedure get_rax(salary in number,rax out number)
as
    --需要交税的钱
    bal number;
begin
    bal := salary - 3500;
    if bal<=1500 then
       rax := bal * 0.03 - 0;
    elsif bal<=4500 then
       rax := bal * 0.1 - 105;
    elsif bal<=9000 then
       rax := bal * 0.2 - 555;
    elsif bal<=35000 then
       rax := bal * 0.25 - 1005;
    elsif bal<=55000 then
       rax := bal * 0.3 - 2755;
    elsif bal<=80000 then
       rax := bal * 0.35 - 5505;
    else
       rax := bal * 0.45 - 13505;
    end if;
end;
/
--调用过程
declare
   --交税
   rax number; 
   salary number := &salary;
begin
   get_rax(salary,rax); 
   dbms_output.put_line(salary||'元工资需要交'||rax||'元税');
end;
/
public class TestCallOracleProc {
    public static void main(String[] args) throws Exception{
        String sql = "{call get_rax(?,?)}";
        Connection conn = JdbcUtil.getConnection();
        CallableStatement cstmt = conn.prepareCall(sql);
        cstmt.setInt(1,10000);
        cstmt.registerOutParameter(2,Types.INTEGER);
        cstmt.execute();
        Integer rax = cstmt.getInt(2);
        System.out.println("10000元需要交" + rax + "元税");
        JdbcUtil.close(cstmt);
        JdbcUtil.close(conn);
    }
}
--定义函数
create or replace function findEmpNameAndJobAndSal(pempno in number,pjob out varchar2,psal out number) 
return varchar2
as
    pename emp.ename%type;
begin
    select ename,job,sal into pename,pjob,psal from emp where empno = pempno;
    return pename;
end;
/
--调用函数
declare
    pename emp.ename%type;
    pjob   emp.job%type;
    psal   emp.sal%type;
begin
    pename := findEmpNameAndJobAndSal(7788,pjob,psal);
    dbms_output.put_line('7788'||'--'||pename||'--'||pjob||'--'||psal);
end;
/
public class TestCallOracleFunc {
    public static void main(String[] args) throws Exception{
        String sql = "{?=call findEmpNameAndJobAndSal(?,?,?)}";
        Connection conn = JdbcUtil.getConnection();
        CallableStatement cstmt = conn.prepareCall(sql);
        cstmt.registerOutParameter(1,Types.VARCHAR);
        cstmt.setInt(2,7788);
        cstmt.registerOutParameter(3,Types.VARCHAR);
        cstmt.registerOutParameter(4,Types.INTEGER);
        cstmt.execute();
        String ename = cstmt.getString(1);
        String job = cstmt.getString(3);
        Integer sal = cstmt.getInt(4);
        System.out.println(ename+":"+job+":"+sal);
        JdbcUtil.close(cstmt);
        JdbcUtil.close(conn);
    }
}

三)mysql的优化

      select emp.empno,emp.ename,emp.sal,salgrade.grade,dept.dname
      from salgrade,dept,emp
      where (emp.deptno = dept.deptno) and (emp.sal between salgrade.losal and salgrade.hisal)          
- 1)如果三个表是完全无关系的话,将记录和列名最少的表,写在最后,然后依次类推
- 2)如果三个表是有关系的话,将引用最多的表,放在最后,然后依次类推

-2)WHERE子句中的连接顺序(笔试常考)
- 数据库采用自右而左的顺序解析WHERE子句,根据这个原理,表之间的连接必须写在其他WHERE条件之左, 那些可以过滤掉最大数量记录的条件必须写在WHERE子句的之右。
- 例如:查询员工的编号,姓名,工资,部门名

      select emp.empno,emp.ename,emp.sal,dept.dname
      from emp,dept
      where (emp.deptno = dept.deptno) and (emp.sal > 1500)   

-3)SELECT子句中避免使用*
- 数据库在解析的过程中,会将*依次转换成所有的列名,这个工作是通过查询数据字典完成的,这意味着将耗费更多的时间 : select empno,ename from emp;

-4)用TRUNCATE替代DELETE

-5)尽量多使用COMMIT : 因为COMMIT会释放回滚点

-6)用WHERE子句替换HAVING子句, WHERE先执行,HAVING后执行

-7)多使用内部函数提高SQL效率

-8)使用表的别名 : salgrade s

-9)使用列的别名 : ename e

上一篇下一篇

猜你喜欢

热点阅读