jquery实现json数据填充到table表格中并且实现remove add 数据


题记:最近做关于OpenDaylight的项目,然还用到了一些前端和javaee的相关技术,本代码实现的是通过数据库部分读到的json数据,数据库部分没有写出,填充到table表格中,并且也可以实现table表格中用户自行进行增删等操作,主要是jquery、js.列出但是参考的资料: http://www.cnblogs.com/lxblog/archive/2013/01/11/2856582.html  

http://hmkcode.com/jquery-each-json/

1html部分 注意js的链接地址,还有jquery版本,jquery如果用1.11.1版本的话,程序运行










    
    
Device Mangement


    
   
   
   
   

Device management

IP Group

2 js部分

  这部分主要实现了几个函数,注意each函数的用法,并且index是从0开始的,注意字符串的拼接,以及双引号嵌套的使用。js或者html中要求是,“  ‘ ’  ” 双引号中是单引号,还有就是向checkbox的id作为一个变量的用法应。其中感觉比较重要的是通过一个json字符串给table显示。(变量一定要“+xx+”v这种形式)
 $("#table").append($('')
.append($('').html(""))
.append($('').html(article.ip))
   .append($('').html(article.group))
$(document).ready(function () {
     //function refreshTable()
	var articles = [
        { 
            "ip":"80.4.2.59",
            "group":"A"
        },
        {
            "ip":" 80.4.2.58 ",
            "group":"B"
        },
		{
            "ip":" 10.75.199.244 ",
            "group":"C"
        }
    ];
    // 1. remove all existing rows
    $("tr:has(td)").remove();
    // 2. get each article //遍历article中的每一个元素
    $.each(articles, function (index, article) {
        // 2.1 Create table column for group
        // 2.2 Create a new row and append 3 columns (ip+url, group, tags)
        $("#table").append($('')
				.append($('').html(""))
				.append($('').html(article.ip))
			    .append($('').html(article.group))
        );  
    });              
	$("#removebtn").bind("click", delOneRow);
    $("#addbtn").bind("click", insertRowLast),
    $("#getbtn").bind("click", getRowlValue),
    $("#table tr:gt(0) td:first-child input:checkbox").bind("click",checkOne);
});
var c=-1;
function checkOne() { //this return is which checkbox is checked
    var allBox = $(":checkbox"); //only choose one
    allBox.click(function () {
        allBox.removeAttr("checked");
        $(this).attr("checked", true);
        });
	var i = $("#table tr:gt(0) td:first-child input:checkbox").length;
    c = -1;
    var j=0;
    $("#table tr:gt(0) td:first-child input:checkbox").each(function () {
    	j+=1;
		if ($(this).attr("checked")==true) {
            //c += 1;//only select one,c is number of select
            var q=1;
			while(i--){
				if(j==q){
				c=j-1;
				return false;
				}
				q++;
			}
         }
     });
}
function delOneRow() {
	//checkOne();//which row
	if(c!=-1)
	{
		$("#table tr:gt(0):eq("+c+")").remove();
	}
}
 function insertRowLast() {
    var diag = new Dialog();
	diag.Title = "please input device information";
	diag.URL = "testeject.html";
	diag.OKEvent = function(){
	var ip = diag.innerFrame.contentWindow.document.getElementById('ip').value;
	var group = diag.innerFrame.contentWindow.document.getElementById('group').value; 
	var newRow = ""+ip+""+group+"";
	$("#table tr:last").after(newRow);
	diag.close();
	};
	//after click ok,oKEvent will be run 
	diag.show();
	var doc=diag.innerFrame.contentWindow.document;
	doc.open();
	doc.write('I   P 


Group'); doc.close(); } function getRowlValue() { var v = ""; //$("#table tr:gt(0):eq(1) td").each(function () { if(c!=-1) { $("#table tr:gt(0):eq("+c+") td").each(function () { v += $(this).text() + " "; }); alert(v); } }

3 diag 部分已经在上面代码写出来,这部分写的不好,希望可以用bootstrap再加工下

附录:工程下载链接地址: 点击打开链接 ,注意有几个html文件,最终调试的是device777.html
4 后来在项目中调试后的是以下的代码部分,增加了模态框并且和服务器通信也成功:
html:










Device Mangement




Name IP Group
4 js部分:
window.οnlοad=function(){
	//var articles = getAllDbdata();
	getAllDbdata();	
    $("#removebtn").bind("click", delOneRow);
    $("#addbtn").bind("click", insertRowLast),
    $("#getbtn").bind("click", getRowlValue),
    $("#editbtn").bind("click", editRowlValue),
    $("#table tr:gt(0) td:first-child input:checkbox").bind("click",checkOne);
};
function getAllDbdata(){
	$("#error-msg").empty();
	var query = JSON.stringify(getQueryInput("get","","",""));
    var get = sendReq("/device/GetDB", query);
    if (get == null){
    	 $("#errro-msg").html('');
    	return;
    }
    var articles1 = get.resultDB;////articles:"[{},{}]" must use eval to [{},{}]
    var articles = JSON.parse(articles1);//both this method and eval() can run  
    //var articles = eval(articles1);//very important.
   //var articles = [{ "name" : "rfswitch1" , "ip" : "80.4.2.59" , "group" : "A"}, { "name" : "rfswitch2" , "ip" : "10.75.199.244" , "group" : "B"}, { "name" : "rfswitch3" , "ip" : "10.75.192.15" , "group" : "B"}, { "name" : "rfswitch2" , "ip" : "192.168.1.3" , "group" : "A"}, { "name" : "frank" , "ip" : "192.168.1.0" , "group" : "frank"}, { "name" : "frank1" , "ip" : "192.168.1.0" , "group" : "frank1"}, { "name" : "frank2" , "ip" : "198.189" , "group" : "C"}, { "name" : "rfswich4" , "ip" : "192.168.1.9" , "group" : "D"}, { "name" : "rfswitch4" , "ip" : "192.168.1.9" , "group" : "D"}, { "name" : "rfswitch3" , "ip" : "192.168.1.9" , "group" : "D"}];
    $("tr:has(td)").remove();
    // 2. get each article
    $.each(articles, function (index, article) {
        // 2.1 Create table column for group
        // 2.2 Create a new row and append 3 columns (ip+url, group, tags)
        $("#table").append($('')
				.append($('').html(""))
				.append($('').html(article.name))			
				.append($('').html(article.ip))
			    .append($('').html(article.group))
        );  
    });
}
var c=-1;
function checkOne() { //this return is which checkbox is checked
    var allBox = $(":checkbox"); //only choose one
    allBox.click(function () {
        allBox.removeAttr("checked");
        $(this).prop("checked", true);
        });
	var i = $("#table tr:gt(0) td:first-child input:checkbox").length;
    c = -1;
    var j=0;
    $("#table tr:gt(0) td:first-child input:checkbox").each(function () {
    	j+=1;
		if ($(this).is(":checked")==true) { //low jquery: attr("checked")
            //c += 1;//only select one,c is number of select
            var q=1;
			while(i--){
				if(j==q){
				c=j-1;
				return false;
				}
				q++;
			}
         }
     });
}
function delOneRow() {
	//checkOne();//which row
	//
	if(c!=-1)
	{
		var arraystr = getRowlValue();
		var name = arraystr[1];
		var ip = arraystr[2];
		var group = arraystr[3];
		var query = JSON.stringify(getQueryInput("remove",name,ip,group));
        var get = sendReq("/device/RemoveDB", query);
        if(get.msg == "failed")
        {
        	  $("#errro-msg").html('');
        	  return;
        }
		//$("#table tr:gt(0):eq("+c+")").remove();
 	   window.location.reload();
	}
}
 function insertRowLast() {
		  $("#modaladd").modal("toggle");
    		$("#modaladd").draggable({
    		    handle: ".modal-header"
    		});
		  $("#addsubmitbutton").click(function(){
	            var query = JSON.stringify(getQueryInput("add","","",""));
	            var get = sendReq("/device/AddDB", query);
	            if (get == null){
	            	return;
	            }
	            if(get.msg != ""){
	            	   $("#errro-msg").html('');
		        	   $('#modaladd').modal('hide');
	            	   return;
	           }
	           if(get.msg == ""){
	        	   $('#modaladd').modal('hide');
		            //getAllDbdata();
	        	   window.location.reload();
	           }
	           return;
	      });
}
function editRowlValue() {
	if(c!= -1){
		var arraystr = getRowlValue();
		$("#inputeditname").val(arraystr[1]);
		$("#inputeditip").val(arraystr[2]);
		$("#inputeditgroup").val(arraystr[3]);
		$("#modaledit").modal("toggle");
		$("#modaledit").draggable({handle: ".modal-header"});//must import jquery-ui.min.js,let modal drag
		 $("#editsubmitbutton").click(function(){
			var name = $("#inputeditname").val();
			var ip = $("#inputeditip").val();
			var group = $("#inputeditgroup").val();
			 var query = JSON.stringify(getQueryInput("edit",name,ip,group));
	          var get = sendReq("/device/EditDB", query);
	          if (get == null){
	          	return;
	          }
	          if(get.msg != ""){
	          	   $("#errro-msg").html('');
		        	   $('#modaledit').modal('hide');
	          	   return;
	         }
	         if(get.msg == ""){
	      	   $('#modaledit').modal('hide');
        	   window.location.reload();
	         }
	         return;
	    });	
	}
}
function getRowlValue() {
    var v = "";
    //$("#table tr:gt(0):eq(1) td").each(function () {
	if(c!=-1)
	{
		$("#table tr:gt(0):eq("+c+") td").each(function () {    
		v += $(this).text() + " ";
		});
	}
	var fenstr = v.split(" ");
	return fenstr;
	
}
function getQueryInput(type,name,ip,group) {
    var input = {
            "name" : null,
            "ip" : null,
            "group" : null
        };
    if(type == "add"){
    	input["name"] = $("#inputaddname").val();
        input["ip"] = $("#inputaddip").val();
        input["group"] = $("#inputaddgroup").val();
    }
    if(type == "remove"){
       	input["name"] = name;
        input["ip"] = ip;
        input["group"] = group;
    }
    if(type == "edit"){
       	input["name"] = name;
        input["ip"] = ip;
        input["group"] = group;
    }
    return { "input" : input };
}
function sendReq(url, query) {
    var req = new XMLHttpRequest();
    req.open("POST", url, false);
    req.setRequestHeader("Content-type","application/json");
    req.send(query.toString());
    if(req.responseText == ""){
    	return null;
    }
    var get_response = jQuery.parseJSON(req.responseText).output;
    return get_response;
}



你可能感兴趣的:(web前端,web前端,jquery)