代码常用

1)  UserApi这个类注册到log,然后就能调用log4j里面的配置进行日志输出

 Logger loger = Logger.getLogger(UserApi.class);

2)使用通配符*,允许所有跨域访问

但是,请注意使用通配符*,会允许来自任意域的跨域请求访问成功,这是比较危险的,所以在生产环境通常会做更精确控制;

 response.setHeader("Access-Control-Allow-Origin", "*");

3)json解析

   String input = new String(getRequestContent(request), "utf-8");
   String s = input.replaceAll("&", ",");
   JSONObject inJson = JSONObject.fromObject(s);
   String phone = inJson.getString("userName");

 

4)获取随机短信验证码

//Math.random():产生一个大于0小于1的小数
String para = (int) ((Math.random() * 9 + 1) * 100000) + "";

5)点击触发模态框

//toggle:点击的时候触发和当前模态窗口状态相反的操作
$("#mymodal").modal("toggle");

//show,指的是点击的时候触发打开窗口
$("#mymodal").modal("show");

//hide,指的是点击的时候触发关闭模态窗
$("#mymodal").modal("hide");

7)通过调用DOM中的reset方法来重置表单

$('#yigeform')[0].reset()

8)序列化提交表单

<form id="form1">
    <input name="username" type="text" value="" />
    <input name="password" type="text" value="" />
 </form>
//把form表单的值序列化成一个字符串,如username=admin&password=admin123
$("#form1").serialize()

//把form表单的值序列化成一个json对象,如{username:admin,password:admin123}
$("#form1").serializeObject()

// 把form表单的值序列化成一个数组,如[ {username:admin,password:admin123},  {username:admin,password:admin123} ]
$("#form1").serializeArray()

//  将字符串解析成Json对象
JSON.parse()

//  将Json对象解析成字符串
JSON.stringify()

        常见问题

      $("#form1"). serialize()后台获取不到表单中属性为disabled的元素的值的解决办法

当属性设置为"disabled"时,提交表单时,select的值无法传递,提交前移除disabled属性$("#conferenceType").removeAttr("disabled"); 即可

9)刷新表格

$("#typegroup").bootstrapTable('refresh');

获取选中的checkbox

 $('#table').bootstrapTable('getSelections')

删除选中行

$("#table").bootstrapTable('removeByUniqueId',id )

批量删除

var ids = $.map($("#table").bootstrapTable('getSelections'), function (row) {
    return row.id
});
if(ids.length==0){
    alert("至少选择一行!")
}else{
    if(confirm("确定要删除选中项?")){
        $("#table").bootstrapTable('remove', {
            field: 'id',
            values: ids
        });
    }

}

10) 设置内容:
          var(): 声明变量

          text(): 设置和返回所选元素的文本内容

          html(): 设置和返回所选元素的内容(包括HTML标记)

          attr():  设置/改变属性值,允许同时设置多个属性。

          alert():使用变量,打印出来

           val(): 设置或返回表单字段的值

11) jquery操作select(取值,设置选中)

<1>基础取值问题   例如<select class="selector"></select>

        1.1)   $(".selector").val("pxx"): 设置value为pxx的项选中

        1.2)设置text为pxx的项选中

               select中: $(".selector").find("option:contains('pxx')").attr("selected",true);

                input中:   $(".selector").find("input[text='pxx']").attr("selected",true);

        1.3)$(".selector").val(): 获取当前选中项的value

        1.4)  $(".selector").find("option:selected").text():获取当前选中项的text

 <2>很多时候用到select的级联,即第二个select的值随着第一个select选中的值变化。这在jquery中是非常简单的。

$(".selector1").change(function(){

     // 先清空第二个

      $(".selector2").empty();

     // 实际的应用中,这里的option一般都是用循环生成多个了

      var option = $("<option>").val(1).text("pxx");

      $(".selector2").append(option);

});

<3>jQuery获取Select选择的Text和Value:

 //为Select添加事件,当选择其中一项时触发
$("#select_id").change(function(){//code...}); 

 //获取Select选择的Text
var checkText=$("#select_id").find("option:selected").text(); 

 //获取Select选择的Value
var checkValue=$("#select_id").val();

//获取Select选择的索引值
var checkIndex=$("#select_id ").get(0).selectedIndex;

//获取Select最大的索引值
var maxIndex=$("#select_id option:last").attr("index"); 

<4>jQuery设置Select选择的 Text和Value:

 //设置Select索引值为1的项选中
$("#select_id ").get(0).selectedIndex=1; 

 // 设置Select的Value值为4的项选中
 $("#select_id ").val(4);   

 //设置Select的Text值为jQuery的项选中
 $("#select_id option[text='jQuery']").attr("selected", true); 

<5> jQuery添加/删除Select的Option项:

 //为Select追加一个Option(下拉项)
 $("#select_id").append("<option value='Value'>Text</option>");

//为Select插入一个Option(第一个位置)
$("#select_id").prepend("<option value='0'>请选择</option>"); 

//删除Select中索引值最大Option(最后一个)
 $("#select_id option:last").remove();

 //删除Select中索引值为0的Option(第一个)
 $("#select_id option[index='0']").remove();  

  //删除Select中Value='3'的Option
 $("#select_id option[value='3']").remove();  

 //删除Select中Text='4'的Option
 $("#select_id option[text='4']").remove(); 

<6>jquery radio取值,checkbox取值,select取值,radio选中,checkbox选中,select选中,及其相关 

//获取一组radio被选中项的值 
var item = $('input[name=items][checked]').val(); 


// 获取select被选中项的文本 
var item = $("select[name=items] option[selected]").text();

 
// select下拉框的第二个元素为当前选中值 
$('#select_id')[0].selectedIndex = 1; 


// radio单选组的第二个元素为当前选中值 
$('input[name=items]').get(1).checked = true; 

<7>获取值

//文本框,文本区域
$(#txt).attr("value")

//多选框checkbox

$("#checkbox_id").attr("value");

//单选组radio

 $("input[type=radio][checked]").val(); 

//下拉框select
 $('#sel').val(); 

<8>控制表单元素

//文本框,文本区域
//清空内容   $("#txt").attr("value",'');
//填充内容: $("#txt").attr("value",'11');


//多选框checkbox: 
 $("#chk1").attr("checked",'');  //不打勾
 $("#chk2").attr("checked",true); //打勾
if($("#chk1").attr('checked')==undefined)  //判断是否已经打勾

//单选组radio
 $("input[type=radio]").attr("checked",'2');//设置value=2的项目为当前选中项 

//下拉框 select:
$("#sel").attr("value",'-sel3'); //设置value=-sel3的项目为当前选中项

$("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel")//添加下拉框的option 
$("#sel").empty();//清空下拉框

12)jquery:attr(),siblings(),find(),index(),$.each()

        12.1)  $.attr():设置或返回被选元素的属性值

                 eg:

                      $("img").attr({src:"",alt:""});

                      $("img").attr("title");

                      $("img").attr("title", function(){});

          12.2)$.siblings()

                  取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。可以用可选的表达式进行筛选。

                   eg:

                        $("div").siblings()       // 找到每个div的所有同辈元素。

                        $("div").siblings(".selected")     // 找到每个div的所有同辈元素中带有selected的元素。

                             // 选择当前项,添加.current类,并选择同级元素,删除.current类

                        $(this).addClass("current").siblings().removeClass("current");     

            12.3) $.find()        

                         搜索所有与制定表达式匹配的元素。找出正在处理的元素的后代元素的方法。

                                   $("div").find("span");

            12.4)$.index()

                          搜索匹配的元素,并返回相应元素的索引值。 从0开始。找不到返回-1。

                          返回的是未知。

                            传递参数:返回参数过滤器相对$对象的位置。

                          不传递参数:返回相对于这个$对象的位置。

                  // 获取当前点击的元素在li中的位置:

                       $("li").index($(this)); 

                //.FixedOddsPlaceBetArea 下面的 div中索引位置等于index的本身显示 其他的隐藏

             $(".FixedOddsPlaceBetArea>.placeBetArea_content:eq(" + index + ")").show().siblings(".placeBetArea_content").hide();

            12.5)$.each() 以每一个匹配的元素作为上下文来执行一个函数。

                              //设置两个图像的属性:

                                $("img").each(function(i) {this.src ="srcnum"+i+".jpg";});

12)设置主键为当前时间戳

taskType.setId(System.currentTimeMillis()+"");

13)FormData实现文件上传实例

    可以使用jquery来发送FormData,但必须要正确的设置相关选项

<div class="tool" style="position:absolute;top:30px;">
        <form id="dataForm" method="post" enctype="multipart/form-data">
            <label  style="display: inline-block;float: left;margin-top: 10px;">任务行业:</label>
            <select id="select1" style="display: inline-block;float: left;text-align: center;text-align-last: center;width:150px;" name="industryId" class="form-control">
                <option value="">--请选择--</option>
            </select>

            <label style="display: inline-block;float: left;margin-top: 10px;">任务类别:</label>
            <input name="typeName" required  style="display: inline-block;float: left;" class="form-control" placeholder="请输入任务类别"/>

            <label style="display: inline-block;float: left;margin-top: 10px;">下限金额:</label>
            <input name="smallMoney" required  style="display: inline-block;float: left;" class="form-control" placeholder="请输入下限金额"/>
            <label style="display: inline-block;float: left;margin-top: 10px;">上限金额:</label>
            <input name="bigMoney" required  style="display: inline-block;float: left;" class="form-control" placeholder="请输入上限金额"/>

            <label style="float:left;margin-left: 30px;margin-top: 10px">照片:</label>
            <input name="typeImg" style="width:100px;float: left; " type="file" class="btn">
            
            <button id="button" onclick="add()" style="display: inline-block;float: left; margin-left: 15px;" type="submit" class="btn btn-info" >添加类别</button>
        </form>
    </div>
  //获取行业分类
    $(function () {
        $.ajax({
            type: "post",
            url: url+"/admin/witkey/getAdminIndustry.action",
            success: function (data) {
                var data = eval(data);
                $.each(data, function (k, col) {
                    $("#select1").append('<option value="' + col.value + '">' + col.options + '</option>');
                })
            }
        })
    });
  //添加
    function add() {
        var form = new FormData(document.getElementById("dataForm"));
        $.ajax({
            url: url+"/admin/TaskType/addTaskType.action",
            data: form,
            type: "post",
            processData: false,   // 告诉jQuery不要去处理发送的数据
            contentType: false,  // 告诉jQuery不要去设置Content-Type请求头
            success: function (data) {
                if (data.rtncode == 0) {
                    alert("添加成功");
                } else {
                    alert("添加失败");
                }
                $("#table").bootstrapTable('refresh');
            }
        });
    }
public class TaskTypeAction extends BaseAction {
    Logger logger = Logger.getLogger(TaskType.class);
    //配置任务类型
    @RequestMapping(value = "/addTaskType.action",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public JSONObject addTaskType(TaskType taskType,@RequestParam("typeImg")MultipartFile typeImg, HttpServletRequest request){
        JSONObject ret = new JSONObject();
        try {
            /*
             *request.getSession().getServletContext():获取的是Servlet容器对象,相当于tomcat容器了
             * getRealPath("/images"):获取实际路径
             * “/”:指代项目根目录
             * 代码返回的是项目在容器中实际发布运行的根路径。
             */
            String path = request.getSession().getServletContext().getRealPath("/images");
            String fileName = System.currentTimeMillis() +typeImg.getOriginalFilename().substring(typeImg.getOriginalFilename().indexOf("."));
            File dir = new File(path, fileName);
            //判断指定的路径或者指定的目录文件是否已经存在
            if(!dir.exists()){
                //创建文件夹
                dir.mkdirs();
            }
            typeImg.transferTo(dir);
             //获取编码
            List<String> list= taskTypeService.getCode();
            if(null!=list&&list.size()>0){
                int i=Integer.parseInt(list.get(list.size()-1))+1;
                taskType.setTypeCode("0"+i);//设置编码code
            }else {
                taskType.setTypeCode("01");
            }
            //设置主键为当前时间戳
            taskType.setId(System.currentTimeMillis()+"");
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = dateformat.format(new Date());//将字符串时间戳转为日期类型
            taskType.setCreateTime(date);
            taskType.setImg(fileName);
            taskTypeService.addEntity(taskType);
            ret.put(Constant.RTN_CODE, Constant.SUCC_CODE);
            ret.put(Constant.RTN_MSG, Constant.SUCC_MSG);
        }catch (Exception e){
            logger.info("添加失败",e);
            ret.put(Constant.RTN_CODE, Constant.DEFAULT_EXCEPTION_CODE);
            ret.put(Constant.RTN_MSG,e.getMessage());
        }
        return ret;
    }

14)数据库中拼接字符模糊查询语句

           concat: 数据库中拼接字符串方法

           distinct: 消除重复行

          group by: 分组排序

//查询所有记录,如果存在和 a 字段相同的记录则只取一条
select distinct a from table;


<select id = "getCabineByVoltage"  parameterType = "CabinetModel" resultMap = "BaseResultMap">
     select * from cabinet_model
   <trim prefix = "where" prefixOverrides = "AND | OR">
        <if text = "voltageType != null and  voltageType != “” "

15)$.each():对数组,json和DOM结构等的遍历

15.1)遍历以为数组

 var arr1=['aa','bb','cc','dd'];
 $.each(arr1,function(i,val){ //两个参数,第一个参数表示遍历的数组的下标,第二个参数表示下标对应的值
 console.log(i+'```````'+val);

//输出结果是
0```````aa
1```````bb
 2```````cc
3```````dd

15.2)遍历二维数组

var arr2=[['aaa','bbb'],['ccc','ddd'],['eee','fff']];
$.each(arr2,function(i,item){ //两个参数,第一个参数表示下标,第二个参数表示一维数组中的每一个数组
 console.log(i+'````'+item);

//输出结果是
0````aaa,bbb
1````ccc,ddd
2````eee,fff

此时可以对输出的一堆二维数组进行遍历

$.each(item,function(i,val){  //遍历二维数组
          console.log(i+'`````'+val);
  })

//输出结果是
0````aaa,bbb
    0`````aaa
    1`````bbb
1````ccc,ddd
    0`````ccc
    1`````ddd
2````eee,fff
    0`````eee
    1`````fff

15.3)处理json

var json1={key1:'a',key2:'b',key3:'c'};
 $.each(json1,function(key,value){  //遍历键值对
            console.log(key+'````'+value);
  })

//输出结果是
key1````a
key2````b
key3````c

15.4)当二维数组中有json对象时

var arr3=[{name:'n1',age:18},{name:'n2',age:20},{name:'n3',age:22}];
        $.each(arr3,function(i,val){
            console.log(i+'`````'+val);   
    //输出
    /* 0`````[object Object] 1`````[object Object] i2`````[object Object]*/
            console.log(val.name); //获取每一个json里面的name值
            console.log(val["name"]);
            $.each(val,function(key,val2){
                console.log(key+'```'+val2);
            })
        });

15.5)处理DOM元素

<input name="aaa" type="hidden" value="111" />
<input name="bbb" type="hidden" value="222" />
<input name="ccc" type="hidden" value="333" />
<input name="ddd" type="hidden" value="444"/>


$.each($('input:hidden'),function(i,val){
            console.log(i+'````'+val);
            /*0````[object HTMLInputElement]
            1````[object HTMLInputElement]
            2````[object HTMLInputElement]
            3````[object HTMLInputElement]*/
            console.log(val.name+'`````'+val.value);
           /* aaa`````111
           bbb`````222
            ccc`````333
           ddd`````444*/
        })

jquery中还有另外一种写法来遍历元素

$("input:hidden").each(function(i,val){  //第一个参数表示索引下标,第二个参数表示当前索引元素
    alert(i);
    alert(val.name);
    alert(val.value);       
});

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值