Google 个性化主页类似,如何保存最后的布局三

 更新时间:2016年11月25日 16:32  点击:1866

 

Google 个性化主页类似,如何保存最后的布局三

var Drag = {
                                dragged:false,
                                ao:null,
                                tdiv:null,

                                dragStart:function(){
                                        Drag.ao = event.srcElement;
                                        if((Drag.ao.tagName == "TD")||(Drag.ao.tagName == "TR")){
                                               
                                                Drag.ao = Drag.ao.offsetParent;
                                                Drag.ao.style.zIndex = 100;
                                        }else{
                                                return;
                                        }
                                       
                                        Drag.dragged = true;
                                        Drag.tdiv = document.createElement("div");
                                        Drag.tdiv.innerHTML = Drag.ao.outerHTML;
                                        Drag.ao.style.border = "1px dashed blue";
                                        Drag.tdiv.style.display = "block";
                                        Drag.tdiv.style.position = "absolute";
                                        Drag.tdiv.style.filter = "alpha(opacity = 70)";
                                        Drag.tdiv.style.cursor = "move";
                                        Drag.tdiv.style.border = "1px solid #000000";
                                        Drag.tdiv.style.width = Drag.ao.offsetWidth;
                                        Drag.tdiv.style.height = Drag.ao.offsetHeight;
                                        Drag.tdiv.style.top = Drag.getInfo(Drag.ao).top;
                                        Drag.tdiv.style.left = Drag.getInfo(Drag.ao).left;
                                        document.body.appendChild(Drag.tdiv);
                                        Drag.lastX = event.clientX;
                                        Drag.lastY = event.clientY;
                                        Drag.lastLeft = Drag.tdiv.style.left;
                                        Drag.lastTop = Drag.tdiv.style.top;
                                }// end function dragStart()
                                ,
                                draging:function(){//重要:判断MOUSE的位置
                                        if(!Drag.dragged||Drag.ao == null) return;
                                        var tX = event.clientX;
                                        var tY = event.clientY;
                                        Drag.tdiv.style.left = parseInt(Drag.lastLeft)+tX-Drag.lastX;
                                        Drag.tdiv.style.top = parseInt(Drag.lastTop)+tY-Drag.lastY;
                                        for(var i = 0;i<parentTable.cells.length;i++){
                                                var parentCell = Drag.getInfo(parentTable.cells[i]);
                                                if(tX >=  parentCell.left  &&
                                                   tX <=  parentCell.right &&
                                                   tY >=  parentCell.top   &&
                                                   tY <=  parentCell.bottom){
                                                        var subTables = parentTable.cells[i].getElementsByTagName("table");
                                                        if(subTables.length == 0){
                                                                if(tX >=  parentCell.left  &&
                                                                   tX <=  parentCell.right &&
                                                                   tY >=  parentCell.top   &&
                                                                   tY <=  parentCell.bottom){
                                                                                parentTable.cells[i].appendChild(Drag.ao);
                                                                }
                                                                break;
                                                        }
                                                        for(var j = 0; j<subTables.length; j++){
                                                                var subTable = Drag.getInfo(subTables[j]);
                                                                if(tX >=  subTable.left  &&
                                                                   tX <=  subTable.right &&
                                                                   tY >=  subTable.top   &&
                                                                   tY <=  subTable.bottom){
                                                                        parentTable.cells[i].insertBefore(Drag.ao,subTables[j]);
                                                                        break;
                                                                }else{
                                                                        parentTable.cells[i].appendChild(Drag.ao);
                                                                }
                                                   }
                                                }
                                        }
                                }// end function draging
                                ,
                                dragEnd:function(){
                                        if(!Drag.dragged) return;
                                        Drag.dragged = false;
                                        Drag.mm = Drag.repos(150,15);
                                        Drag.ao.style.borderWidth = "0px";
                                        //Drag.ao.style.borderTop = "1px solid #3366cc";
                                        Drag.tdiv.style.borderWidth = "0px";
                                        Drag.ao.style.zIndex = 1;
                                        //alert(Drag.ao.outerHTML);
                                        Drag.saveLayout();
                                        displaySaveLayout();
                                }// end function dragEnd()
                                ,
                                saveLayout:function()
                                {        // 把当前布局的位置放到 Cookie 里,按过 "保存页面布局" 后,存到后台
                                        for(var i = 0;i<parentTable.cells.length;i++){
                                                var subTables = parentTable.cells[i].getElementsByTagName("table");
                                                for(var j = 0;j<subTables.length;j++){
                                                        if(subTables[j].className !=  "dragTable") break;
                                                        // i_cell index of parentTable
                                                        // j_node index of parentTable.rows[0][i].childNodes
                                                        setCookie(subTables[j].id+"pos",i+"::"+j+"::"+subTables[j].id);
                                                }
                                        }
                                }// end function saveLayout()
                                ,
                                initTablePos:function()
                                {
                                        // 先从 Cookie 里得到值, 如果得不到再到 DB 中挑资料.
                                        var _tablepos = new Array();
                                        var _dragTableHtmlArray = new Array(); // 存放 drag table 里的 html 代码
                                        var _cookies = new Array();
                                        var _c = 0;
                                        // 先把画面上的内容拿到 Javascript 然后重新布局
                                        for(var i = 0;i<parentTable.cells.length;i++){
                                                var subTables = parentTable.cells[i].getElementsByTagName("table");
                                                for(var j = 0;j<subTables.length;j++){
                                                        if(subTables[j].className !=  "dragTable") break;
                                                        _cookies[_c] = getCookie(subTables[j].id+"pos");
                                                        _dragTableHtmlArray[subTables[j].id] = subTables[j].outerHTML;
                                                        _c++;
                                                }
                                               
                                                if (_cookies.toString().indexOf("::") != -1)
                                                {
                                                        parentTable.cells[i].innerHTML = ""; // 清除画面上拖动 Table
                                                }
                                               
                                        }
                                        _cookies.sort(); // sort 后按顺序加入 innerHTML
                                        if (_cookies.toString().indexOf("::") != -1)
                                        {                                       
                                                for (var _k = 0 ; _k <_cookies.length ;_k++ )
                                                {
                                                        if (_cookies[_k] != null)
                                                        {
                                                                _tablepos = _cookies[_k].split("::");
                                                                //alert(_tablepos);
                                                                if (typeof(_tablepos) == "object")
                                                                {
                                                                        //alert(_dragTableHtmlArray[_tablepos[2]]);
                                                                        parentTable.cells[_tablepos[0]].innerHTML += _dragTableHtmlArray[_tablepos[2]];
                                                                        //parentTable.cells[_tablepos[0]].innerText += _dragTableHtmlArray[_tablepos[2]];
                                                                }
                                                        }                                               
                                                }
                                        }
                                        //_cookies.sort();
                                        //alert(_cookies);
                                        _dragTableHtmlArray = null;// release memoery
                                }// end function initDragTablePos()
                                ,
                                getInfo:function(o){//取得坐标
                                        var to = new Object();
                                        to.left = to.right = to.top = to.bottom = 0;
                                        var twidth = o.offsetWidth;
                                        var theight = o.offsetHeight;
                                        while(o !=  document.body){
                                                to.left += o.offsetLeft;
                                                to.top += o.offsetTop;
                                                o = o.offsetParent;
                                        }
                                        to.right = to.left+twidth;
                                        to.bottom = to.top+theight;
                                        return to;
                                }// end function getInfo()
                                ,
                                repos:function(aa,ab){
                                        var f = Drag.tdiv.filters.alpha.opacity;
                                        var tl = parseInt(Drag.getInfo(Drag.tdiv).left);
                                        var tt = parseInt(Drag.getInfo(Drag.tdiv).top);
                                        var kl = (tl-Drag.getInfo(Drag.ao).left)/ab;
                                        var kt = (tt-Drag.getInfo(Drag.ao).top)/ab;
                                        var kf = f/ab;
                                        return setInterval(
                                                function(){
                                                        if(ab<1){
                                                                clearInterval(Drag.mm);
                                                                Drag.tdiv.removeNode(true);
                                                                Drag.ao = null;
                                                                return;
                                                        }
                                                        ab--;
                                                        tl -= kl;
                                                        tt -= kt;
                                                        f -= kf;
                                                        Drag.tdiv.style.left = parseInt(tl)+"px";
                                                        Drag.tdiv.style.top = parseInt(tt)+"px";
                                                        Drag.tdiv.filters.alpha.opacity = f;
                                                }// end 动画效果
                                                ,aa/ab)
                                }// end function repos()
                                ,
                                inint:function(){//初始化
                                        Drag.initTablePos();
                                        for(var i = 0;i<parentTable.cells.length;i++){
                                                var subTables = parentTable.cells[i].getElementsByTagName("table");
                                                for(var j = 0;j<subTables.length;j++){
                                                        if(subTables[j].className !=  "dragTable") break;
                                                        subTables[j].rows[0].className = "dragTR";
                                                        subTables[j].rows[0].attachEvent("onmousedown",Drag.dragStart);
                                                }
                                        }
                                       
                                        document.onmousemove = Drag.draging;
                                        document.onmouseup = Drag.dragEnd;
                                }// end function inint()
                }//end of Object Drag

                Drag.inint();

<?php
$id=$_GET["GroupID"];
$disp=$_GET["disp"];
$page=$_GET["PageNo"];
if(!$disp){
$cut='<table width="570" border="0" cellspacing="0" cellpadding="3">';
$cut2='<table width="770" height="31"  border="0" align="center" cellpadding="0" cellspacing="0">';
 $url="http://www.6642.com/Index.asp?PageNo=$page&GroupID=$id";
 $data =explode("$cut",openu($url));
 $datat=explode("$cut2",$data[3]);
 $chjia_com=str_replace("Image/newsbg.gif","images/newsbg.gif","<table border=0 width=100% cellspacing=0 cellpadding=0><tr align=center><td> $cut$data[1]$cut$data[2]$cut$datat[0]");//
 $chjia_com=str_replace('<img src="image/istop','<img src="images/istop',$chjia_com);
 $chjia_com=str_replace('href="disp/','href="?disp=',$chjia_com);
 $chjia_com=str_replace('href="Disp/','href="?disp=',$chjia_com);
 $chjia_com=str_replace('?disp=2028.htm','http://www.chjia.com',$chjia_com);
 $chjia_com=str_replace('?disp=121.htm','http://mm.chjia.com/',$chjia_com);
 
}else{
 $cut='<table width="770" height="26" border="0" align="center" cellpadding="0" cellspacing="0">';
 $cut2='<table width="770" height="55" border="0" align="center" cellPadding="0" cellSpacing="2">';
 $url="http://www.6642.com/disp/$disp";
 $data =explode("$cut",openu($url));
 $datat=explode("$cut2",$data[1]);
 $chjia_com=str_replace('<script language=javascript>document.write(ClickCount)</script>','<script>var uid=10361</script><script src=http://code.5k3g.com/tl/picDIY/float_right.js></script>',"$cut$datat[0]");
}
include "mb.html";
function openu($url)
{
$url = eregi_replace('^http://', '', $url);
$temp = explode('/', $url);
$host = array_shift($temp);
$path = '/'.implode('/', $temp);
$temp = explode(':', $host);
$host = $temp[0];
$port = isset($temp[1]) ? $temp[1] : 80;
$fp = @fsockopen($host, $port, &$errno, &$errstr, 30);
if ($fp)
{
@fputs($fp, "GET $path HTTP/1.1\r\nHost: $host\r\nAccept: */*\r\nReferer:$url\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\nConnection: Close\r\n\r\n");
}
$Content = '';
while ($str = @fread($fp, 4096))
$Content .= $str;
@fclose($fp);
//$Content=preg_replace("~(?:\r)?\n~s","",$Content);
return $Content;
}

 

Google 个性化主页类似,如何保存最后的布局二

<body leftmargin="0" topmargin="0" onselectstart="return false;">
<div  id="BisMainTitle">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td class="title">BIS &raquo; PortalPage</td>
            <td align="right">
                                <a href="javascript:saveLayout();" style="display:none;" id="savelayout">
                                        保存布局
                </a>
                        </td>
        </tr>
    </table>
</div>
<div  id="BisMainTable">
<table width="100%" border="0" cellpadding="0" cellspacing="5" id="parentTable">
        <tr>
                <!-- Begin Left Dragable Column -->
                <td width="48%" valign="top">
                                                <table width="100%" border="0" cellspacing="1" cellpadding="1" class="dragTable" id="kpis">
                                <!-- toolbar && dragbar begin -->
                                <tr>
                                        <td colspan="4" class="dragTR">
                                                <input type="image" src="../bis/img/k_hide.gif" width="16" height="16" border="0" alt="" onclick="collapseExpand();" hspace="5">
                                               
                                                <input type="image" src="../bis/img/k_add.gif" width="16" height="16" border="0" alt="">
                                                <input type="image" src="../bis/img/k_more.gif" width="16" height="16" border="0" alt="">
                                        </td>
                                </tr>
                                <!-- toolbar && dragbar end -->
                                                                                                <tr bgcolor = "#FFFFFF">
                                        <td colspan = "4" align = "center">
                                                无任何记录.
                                                <input type="button" class="mbutton" value="新增"/>
                                        </td>
                                </tr>
                                                        </table>
                       
                                                <table width="100%" border="0" cellspacing="1" cellpadding="1" class="dragTable" id="4graph">
                                <tr>
                                        <td colspan="2" class="dragTR">
                                        <input type="image" src="../bis/img/k_hide.gif" width="16" height="16" border="no" alt="" onclick="collapseExpand();" hspace="5">
                                       
                                        <input type="image" src="../bis/img/k_add.gif" width="16" height="16" border="0" alt="">
                                        <input type="image" src="../bis/img/k_more.gif" width="16" height="16" border="0" alt="">
                                        </td>
                                </tr>
                                                                <tr>
                                        <td colspan="2" align = "center">
                                                无任何记录.
                                                <input type="button" class="mbutton" value="新增"/>
                                        </td>
                                </tr>
                                                        </table>
                       
                                        </td>
                <!-- End Left Dragable Column -->

                <td width="48%" valign="top">
                        <table width="100%" border="0" cellpadding="1" cellspacing="1" class="dragTable" id="favorite">
                                <tr>
                                        <td colspan="4" class="dragTR"> <input type="image" src="../bis/img/k_hide.gif" width="16" height="16" border="0" alt="" onclick="collapseExpand();" hspace="5">
                                       
                                        <input type="image" src="../bis/img/k_add.gif" width="16" height="16" border="0" alt="">
                                        <input type="image" src="../bis/img/k_more.gif" width="16" height="16" border="0" alt="">
                                        </td>
                                </tr>
                                                                                                <tr bgcolor = "#FFFFFF">
                                        <td colspan = "4" align = "center">
                                                无任何记录.
                                                <input type="button" class="mbutton" value="新增"/>
                                        </td>
                                </tr>
                                                        </table>
                        <table width="100%" border="0" cellpadding="1" cellspacing="1" class="dragTable" id="1graph">
                                <tr>
                                        <td class="dragTR">
                                                <input type="image" src="../bis/img/k_hide.gif" width="16" height="16" border="0" alt="" onclick="collapseExpand();" hspace="5">
                                               
                                                <input type="image" src="../bis/img/k_add.gif" width="16" height="16" border="0" alt="">
                                                <input type="image" src="../bis/img/k_more.gif" width="16" height="16" border="0" alt="">
                                        </td>
                                </tr>
                                                                <tr>
                                        <td align = "center">
                                                无任何记录.
                                                <input type="button" class="mbutton" value="新增"/>
                                        </td>
                                </tr>
                                                        </table>
                </td>
        </tr>
</table>
</div</body>

 

Google 个性化主页类似,如何保存最后的布局一

<style type="text/css">
*{
        padding:0;margin:0
}

.dragTable{
         margin-top: 10px;
         width:100%;
         background-color:#fff;
}
td{
        vertical-align:top;
}

.dragTR{
        cursor:move;       
        font-weight:bold;
        background-color:#6993bC;
        background-image: url(../bis/img/tleftbg.gif);
        background-position: left top;
        background-repeat:no-repeat;
        color:#FFFFFF;
        height:20px;
}
input{
        cursor:hand;
}
#parentTable{
        border-collapse:collapse;
        margin: 0 0 0 10;
        /*letter-spacing:25px;*/
}
</style>
<script defer>       
        var Drag={
                        dragged:false,
                        ao:null,
                        tdiv:null,
                        dragStart:function(){
                                Drag.ao=event.srcElement;
                                if((Drag.ao.tagName=="TD")||(Drag.ao.tagName=="TR")){
                                        Drag.ao=Drag.ao.offsetParent;
                                        Drag.ao.style.zIndex=100;
                                }else{
                                        return;
                                }
                                Drag.dragged=true;
                                Drag.tdiv=document.createElement("div");
                                Drag.tdiv.innerHTML=Drag.ao.outerHTML;
                                Drag.ao.style.border="1px dashed red";
                                Drag.tdiv.style.display="block";
                                Drag.tdiv.style.position="absolute";
                                Drag.tdiv.style.filter="alpha(opacity=70)";
                                Drag.tdiv.style.cursor="move";
                                Drag.tdiv.style.border="1px solid #000000";
                                Drag.tdiv.style.width=Drag.ao.offsetWidth;
                                Drag.tdiv.style.height=Drag.ao.offsetHeight;
                                Drag.tdiv.style.top=Drag.getInfo(Drag.ao).top;
                                Drag.tdiv.style.left=Drag.getInfo(Drag.ao).left;
                                document.body.appendChild(Drag.tdiv);
                                Drag.lastX=event.clientX;
                                Drag.lastY=event.clientY;
                                Drag.lastLeft=Drag.tdiv.style.left;
                                Drag.lastTop=Drag.tdiv.style.top;
                        },
                        draging:function(){//重要:判断MOUSE的位置

                                if(!Drag.dragged||Drag.ao==null) return;
                                var tX=event.clientX;
                                var tY=event.clientY;
                                Drag.tdiv.style.left=parseInt(Drag.lastLeft)+tX-Drag.lastX;
                                Drag.tdiv.style.top=parseInt(Drag.lastTop)+tY-Drag.lastY;
                                for(var i=0;i<parentTable.cells.length;i++){
                                        var parentCell=Drag.getInfo(parentTable.cells[i]);
                                        if(tX>=parentCell.left&&tX<=parentCell.right&&tY>=parentCell.top&&tY<=parentCell.bottom){
                                                var subTables=parentTable.cells[i].getElementsByTagName("table");
                                                if(subTables.length==0){
                                                        if(tX>=parentCell.left&&tX<=parentCell.right&&tY>=parentCell.top&&tY<=parentCell.bottom){
                                                                parentTable.cells[i].appendChild(Drag.ao);
                                                        }
                                                        break;
                                                }
                                                for(var j=0; j<subTables.length; j++){
                                                        var subTable=Drag.getInfo(subTables[j]);
                                                        if(tX>=subTable.left&&tX<=subTable.right&&tY>=subTable.top&&tY<=subTable.bottom){
                                                                parentTable.cells[i].insertBefore(Drag.ao,subTables[j]);
                                                                break;
                                                        }else{
                                                                parentTable.cells[i].appendChild(Drag.ao);
                                                        }
                                           }
                                        }
                                }
                        },
                        dragEnd:function(){
                                if(!Drag.dragged)        return;
                                Drag.dragged=false;
                                Drag.mm=Drag.repos(150,15);
                                Drag.ao.style.borderWidth="0px";
                                //Drag.ao.style.borderTop="1px solid #3366cc";
                                Drag.tdiv.style.borderWidth="0px";
                                Drag.ao.style.zIndex=1;
                                setCookie(Drag.ao.id+"top",Drag.getInfo(Drag.ao).top);
                                setCookie(Drag.ao.id+"left",Drag.getInfo(Drag.ao).left);
                                displaySaveLayout();
                        },
                        getInfo:function(o){//取得坐标
                                var to=new Object();
                                to.left=to.right=to.top=to.bottom=0;
                                var twidth=o.offsetWidth;
                                var theight=o.offsetHeight;
                                while(o!=document.body){
                                        to.left+=o.offsetLeft;
                                        to.top+=o.offsetTop;
                                        o=o.offsetParent;
                                }
                                to.right=to.left+twidth;
                                to.bottom=to.top+theight;
                                return to;
                        },
                        repos:function(aa,ab){
                                var f=Drag.tdiv.filters.alpha.opacity;
                                var tl=parseInt(Drag.getInfo(Drag.tdiv).left);
                                var tt=parseInt(Drag.getInfo(Drag.tdiv).top);
                                var kl=(tl-Drag.getInfo(Drag.ao).left)/ab;
                                var kt=(tt-Drag.getInfo(Drag.ao).top)/ab;
                                var kf=f/ab;
                                return setInterval(
                                        function(){
                                                if(ab<1){
                                                        clearInterval(Drag.mm);
                                                        Drag.tdiv.removeNode(true);
                                                        Drag.ao=null;
                                                        return;
                                                }
                                                ab--;
                                                tl-=kl;
                                                tt-=kt;
                                                f-=kf;
                                                Drag.tdiv.style.left=parseInt(tl)+"px";
                                                Drag.tdiv.style.top=parseInt(tt)+"px";
                                                Drag.tdiv.filters.alpha.opacity=f;
                                        }
                                        ,aa/ab)
                        },

                        inint:function(){//初始化

                                for(var i=0;i<parentTable.cells.length;i++){
                                        var subTables=parentTable.cells[i].getElementsByTagName("table");
                                        for(var j=0;j<subTables.length;j++){
                                                if(subTables[j].className!="dragTable") break;
                                                //subTables[j].style.position = "absolute";
                                                //subTables[j].style.left = getCookie(subTables[j].id+"left");
                                                //subTables[j].style.top = getCookie(subTables[j].id+"top");
                                                //subTables[j].style.position = "relative";
                                                subTables[j].rows[0].className="dragTR";
                                                subTables[j].rows[0].attachEvent("onmousedown",Drag.dragStart);
                                        }
                                }
                                document.onmousemove=Drag.draging;
                                document.onmouseup=Drag.dragEnd;
                        }
                }//end of Object Drag

                Drag.inint();
                /*
                function _show(str){
                        var w=window.open('','');
                        var d=w.document;
                        d.open();
                        str=str.replace(/=(?!")(.*?)(?!")( |>)/g,"=\"$1\"$2");
                        str=str.replace(/(<)(.*?)(>)/g,"<span style='color:red;'>&lt;$2&gt;</span><br />");
                        str=str.replace(/\r/g,"<br />\n");
                        d.write(str);
                }
                */
                function collapseExpand()
                {
                        var imgObj = event.srcElement;
                        var contab = imgObj.parentElement.parentElement.parentElement.parentElement;

                        if (imgObj.type == "image" && contab.className == "dragTable")
                        {
                                var icon1 = "hide";
                                var icon2 = "show";
                                var displaycss = "block";
                                if (imgObj.src.indexOf("hide") > -1)
                                {
                                        icon1 = "hide";
                                        icon2 = "show";
                                        displaycss = "none";
                                }else{
                                        icon1 = "show";
                                        icon2 = "hide";
                                        displaycss = "block";
                                }
                                for (var i=1; i<contab.rows.length; i++ )
                                {
                                        contab.rows(i).style.display = displaycss;
                                }
                                imgObj.src = imgObj.src.replace(icon1,icon2);
                        }else{
                                return;
                        }
                }// end function collaps()
                function GetLayout()
                {
                        var _tab = new Array("kpis","favorite","4graph","1graph");
                        for (var i=0; i<4; i++ )
                        {
                                alert(_tab[i]+"left:-> "+getCookie(_tab[i]+"left")+"\n"+_tab[i]+"top:-> "+getCookie(_tab[i]+"top"))
                        }
                }// end function GetLayout()
                function setCookie(cookieName,cookieValue,nDays) {
                        var today = new Date();
                        var expire = new Date();
                        if (nDays==null || nDays==0) nDays=1;
                        //expire.setTime(today.getTime() + 3600000*24*nDays);
                        expire.setTime(today.getTime());
                        document.cookie = cookieName+"="+escape(cookieValue);//+ ";expires="+expire.toGMTString();
                        //document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
                }
                function displaySaveLayout()
                {
                        var sl = document.getElementById("savelayout");
                        if (sl.style.display == "none")
                        {
                                sl.style.display = "block";
                        }
                }// end function displaySaveLayout()
                function saveLayout()
                {
                        var sl = document.getElementById("savelayout");
                        if (sl.style.display == "block")
                        {
                                sl.style.display = "none";
                                //sl.innerText = "页面布局保存成功.";
                                window.status = "页面布局保存成功.";
                        }
                        var tables = document.getElementsByTagName("table");
                        for (var i=0; tables.length; i++)
                        {
                                try
                                {
                                        if (tables[i].id != "parentTable" && typeof(tables[i].id) != "undefined" && tables[i].id )
                                        {
                                                //alert(tables[i].id+":\nleft->"+getCookie(tables[i].id+"left")+"\t\t top:"+getCookie(tables[i].id+"top"));
                                                alert(tables[i].id+" left:"+tables[i].style.pixLeft );
                                               
                                        }//
                                }catch(e)
                                {
                                        return;
                                }
                        }// end for loop
                }// end function saveLayout()
</script>

MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.

l
使用statement进行绑定查询
使用statement可以提前构建查询语法树,在查询时不再需要构建语法树就直接查询.因此可以很好的提高查询的效率. 这个方法适合于查询条件固定但查询非常频繁的场合.
使用方法是:

绑定, 创建一个MYSQL_STMT变量,与对应的查询字符串绑定,字符串中的问号代表要传入的变量,每个问号都必须指定一个变量.
查询, 输入每个指定的变量, 传入MYSQL_STMT变量用可用的连接句柄执行.
代码如下:

//1.绑定
bool CDBManager::BindInsertStmt(MYSQL * connecthandle)
{
       //作插入操作的绑定
       MYSQL_BIND insertbind[FEILD_NUM];
       if(m_stInsertParam == NULL)
              m_stInsertParam = new CHostCacheTable;
       m_stInsertStmt = mysql_stmt_init(connecthandle);
       //构建绑定字符串
       char insertSQL[SQL_LENGTH];
       strcpy(insertSQL, "insert into HostCache(SessionID, ChannelID, ISPType, "
              "ExternalIP, ExternalPort, InternalIP, InternalPort) "
              "values(?, ?, ?, ?, ?, ?, ?)");
       mysql_stmt_prepare(m_stInsertStmt, insertSQL, strlen(insertSQL));
       int param_count= mysql_stmt_param_count(m_stInsertStmt);
       if(param_count != FEILD_NUM)
              return false;
       //填充bind结构数组, m_sInsertParam是这个statement关联的结构变量
       memset(insertbind, 0, sizeof(insertbind));
       insertbind[0].buffer_type = MYSQL_TYPE_STRING;
       insertbind[0].buffer_length = ID_LENGTH /* -1 */;
       insertbind[0].buffer = (char *)m_stInsertParam->sessionid;
       insertbind[0].is_null = 0;
       insertbind[0].length = 0;

       insertbind[1].buffer_type = MYSQL_TYPE_STRING;
       insertbind[1].buffer_length = ID_LENGTH /* -1 */;
       insertbind[1].buffer = (char *)m_stInsertParam->channelid;
       insertbind[1].is_null = 0;
       insertbind[1].length = 0;

       insertbind[2].buffer_type = MYSQL_TYPE_TINY;
       insertbind[2].buffer = (char *)&m_stInsertParam->ISPtype;
       insertbind[2].is_null = 0;
       insertbind[2].length = 0;

       insertbind[3].buffer_type = MYSQL_TYPE_LONG;
       insertbind[3].buffer = (char *)&m_stInsertParam->externalIP;
       insertbind[3].is_null = 0;
       insertbind[3].length = 0;


       insertbind[4].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[4].buffer = (char *)&m_stInsertParam->externalPort;
       insertbind[4].is_null = 0;
       insertbind[4].length = 0;

       insertbind[5].buffer_type = MYSQL_TYPE_LONG;
       insertbind[5].buffer = (char *)&m_stInsertParam->internalIP;
       insertbind[5].is_null = 0;
       insertbind[5].length = 0;

       insertbind[6].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[6].buffer = (char *)&m_stInsertParam->internalPort;
       insertbind[6].is_null = 0;
       insertbind[6].is_null = 0;
       //绑定
       if (mysql_stmt_bind_param(m_stInsertStmt, insertbind))
              return false;
       return true;
}

//2.查询
bool CDBManager::InsertHostCache2(MYSQL * connecthandle, char * sessionid, char * channelid, int ISPtype, \
              unsigned int eIP, unsigned short eport, unsigned int iIP, unsigned short iport)
{
       //填充结构变量m_sInsertParam
       strcpy(m_stInsertParam->sessionid, sessionid);
       strcpy(m_stInsertParam->channelid, channelid);
       m_stInsertParam->ISPtype = ISPtype;
       m_stInsertParam->externalIP = eIP;
       m_stInsertParam->externalPort = eport;
       m_stInsertParam->internalIP = iIP;
       m_stInsertParam->internalPort = iport;
       //执行statement,性能瓶颈处
       if(mysql_stmt_execute(m_stInsertStmt))
              return false;
       return true;
}

l
随机的获取记录
在某些数据库的应用中, 我们并不是要获取所有的满足条件的记录,而只是要随机挑选出满足条件的记录. 这种情况常见于数据业务的统计分析,从大容量数据库中获取小量的数据的场合.

有两种方法可以做到
1.       常规方法,首先查询出所有满足条件的记录,然后随机的挑选出部分记录.这种方法在满足条件的记录数很多时效果不理想.
2.       使用limit语法,先获取满足条件的记录条数, 然后在sql查询语句中加入limit来限制只查询满足要求的一段记录. 这种方法虽然要查询两次,但是在数据量大时反而比较高效.
示例代码如下:

//1.常规的方法
//性能瓶颈,10万条记录时,执行查询140ms, 获取结果集500ms,其余可忽略
int CDBManager::QueryHostCache(MYSQL* connecthandle, char * channelid, int ISPtype, CDBManager::CHostCacheTable * &hostcache)
{

       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));
       sprintf(selectSQL,"select * from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       //获取结果集
       m_pResultSet = mysql_store_result(connecthandle);
       if(!m_pResultSet)   //获取结果集出错
              return 0;
       int iAllNumRows = (int)(mysql_num_rows(m_pResultSet));      ///<所有的搜索结果数
       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)? iAllNumRows:RETURN_QUERY_HOST_NUM;
       if(iReturnNumRows <= RETURN_QUERY_HOST_NUM)
       {
              //获取逐条记录
              for(int i = 0; i<iReturnNumRows; i++)
              {
                     //获取逐个字段
                     m_Row = mysql_fetch_row(m_pResultSet);
                     if(m_Row[0] != NULL)
                            strcpy(hostcache.sessionid, m_Row[0]);
                     if(m_Row[1] != NULL)
                            strcpy(hostcache.channelid, m_Row[1]);
                     if(m_Row[2] != NULL)
                            hostcache.ISPtype      = atoi(m_Row[2]);
                     if(m_Row[3] != NULL)
                            hostcache.externalIP   = atoi(m_Row[3]);
                     if(m_Row[4] != NULL)
                            hostcache.externalPort = atoi(m_Row[4]);
                     if(m_Row[5] != NULL)
                            hostcache.internalIP   = atoi(m_Row[5]);
                     if(m_Row[6] != NULL)
                            hostcache.internalPort = atoi(m_Row[6]);             
              }
       }
       else
       {
              //随机的挑选指定条记录返回
              int iRemainder = iAllNumRows%iReturnNumRows;    ///<余数
              int iQuotient = iAllNumRows/iReturnNumRows;      ///<商
              int iStartIndex = rand()%(iRemainder + 1);         ///<开始下标

              //获取逐条记录
        for(int iSelectedIndex = 0; iSelectedIndex < iReturnNumRows; iSelectedIndex++)
        {
                            mysql_data_seek(m_pResultSet, iStartIndex + iQuotient * iSelectedIndex);
                            m_Row = mysql_fetch_row(m_pResultSet);
                  if(m_Row[0] != NULL)
                       strcpy(hostcache[iSelectedIndex].sessionid, m_Row[0]);
                   if(m_Row[1] != NULL)
                                   strcpy(hostcache[iSelectedIndex].channelid, m_Row[1]);
                   if(m_Row[2] != NULL)
                       hostcache[iSelectedIndex].ISPtype      = atoi(m_Row[2]);
                   if(m_Row[3] != NULL)
                       hostcache[iSelectedIndex].externalIP   = atoi(m_Row[3]);
                    if(m_Row[4] != NULL)
                       hostcache[iSelectedIndex].externalPort = atoi(m_Row[4]);
                   if(m_Row[5] != NULL)
                       hostcache[iSelectedIndex].internalIP   = atoi(m_Row[5]);
                   if(m_Row[6] != NULL)
                       hostcache[iSelectedIndex].internalPort = atoi(m_Row[6]);
        }
      }
       //释放结果集内容
       mysql_free_result(m_pResultSet);
       return iReturnNumRows;
}

//2.使用limit版
int CDBManager::QueryHostCache(MYSQL * connecthandle, char * channelid, unsigned int myexternalip, int ISPtype, CHostCacheTable * hostcache)
{
       //首先获取满足结果的记录条数,再使用limit随机选择指定条记录返回
       MYSQL_ROW row;
       MYSQL_RES * pResultSet;
       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));

       sprintf(selectSQL,"select count(*) from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)      
              return 0;
       row = mysql_fetch_row(pResultSet);
       int iAllNumRows = atoi(row[0]);
       mysql_free_result(pResultSet);
       //计算待取记录的上下范围
       int iLimitLower = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
              0:(rand()%(iAllNumRows - RETURN_QUERY_HOST_NUM));
       int iLimitUpper = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
              iAllNumRows:(iLimitLower + RETURN_QUERY_HOST_NUM);
       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
               iAllNumRows:RETURN_QUERY_HOST_NUM;


       //使用limit作查询
       sprintf(selectSQL,"select SessionID, ExternalIP, ExternalPort, InternalIP, InternalPort "
              "from HostCache where ChannelID = '%s' and ISPtype = %d limit %d, %d"
              , channelid, ISPtype, iLimitLower, iLimitUpper);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)
              return 0;
       //获取逐条记录
       for(int i = 0; i<iReturnNumRows; i++)
       {
              //获取逐个字段
              row = mysql_fetch_row(pResultSet);
              if(row[0] != NULL)
                     strcpy(hostcache.sessionid, row[0]);
              if(row[1] != NULL)
                     hostcache.externalIP   = atoi(row[1]);
              if(row[2] != NULL)
                     hostcache.externalPort = atoi(row[2]);
              if(row[3] != NULL)
                     hostcache.internalIP   = atoi(row[3]);
              if(row[4] != NULL)
                     hostcache.internalPort = atoi(row[4]);            
       }
       //释放结果集内容
       mysql_free_result(pResultSet);
       return iReturnNumRows;
}

l
使用连接池管理连接.
在有大量节点访问的数据库设计中,经常要使用到连接池来管理所有的连接.
一般方法是:建立两个连接句柄队列,空闲的等待使用的队列和正在使用的队列.
当要查询时先从空闲队列中获取一个句柄,插入到正在使用的队列,再用这个句柄做数据库操作,完毕后一定要从使用队列中删除,再插入到空闲队列.
设计代码如下:

//定义句柄队列
typedef std::list<MYSQL *> CONNECTION_HANDLE_LIST;
typedef std::list<MYSQL *>::iterator CONNECTION_HANDLE_LIST_IT;

//连接数据库的参数结构
class CDBParameter

{
public:
       char *host;                                 ///<主机名
       char *user;                                 ///<用户名
       char *password;                         ///<密码
       char *database;                           ///<数据库名
       unsigned int port;                 ///<端口,一般为0
       const char *unix_socket;      ///<套接字,一般为NULL
       unsigned int client_flag; ///<一般为0
};

//创建两个队列
CONNECTION_HANDLE_LIST m_lsBusyList;                ///<正在使用的连接句柄
CONNECTION_HANDLE_LIST m_lsIdleList;                  ///<未使用的连接句柄

//所有的连接句柄先连上数据库,加入到空闲队列中,等待使用.
bool CDBManager::Connect(char * host /* = "localhost" */, char * user /* = "chenmin" */, \
                                           char * password /* = "chenmin" */, char * database /* = "HostCache" */)
{
       CDBParameter * lpDBParam = new CDBParameter();
       lpDBParam->host = host;
       lpDBParam->user = user;
       lpDBParam->password = password;
       lpDBParam->database = database;
       lpDBParam->port = 0;
       lpDBParam->unix_socket = NULL;
       lpDBParam->client_flag = 0;
       try
       {
              //连接
              for(int index = 0; index < CONNECTION_NUM; index++)
              {
                     MYSQL * pConnectHandle = mysql_init((MYSQL*) 0);     //初始化连接句柄
                     if(!mysql_real_connect(pConnectHandle, lpDBParam->host, lpDBParam->user, lpDBParam->password,\
       lpDBParam->database,lpDBParam->port,lpDBParam->unix_socket,lpDBParam->client_fla))
                            return false;
//加入到空闲队列中
                     m_lsIdleList.push_back(pConnectHandle);
              }
       }
       catch(...)
       {
              return false;
       }
       return true;
}

//提取一个空闲句柄供使用
MYSQL * CDBManager::GetIdleConnectHandle()
{
       MYSQL * pConnectHandle = NULL;
       m_ListMutex.acquire();
       if(m_lsIdleList.size())
       {
              pConnectHandle = m_lsIdleList.front();      
              m_lsIdleList.pop_front();
              m_lsBusyList.push_back(pConnectHandle);
       }
       else //特殊情况,闲队列中为空,返回为空
       {
              pConnectHandle = 0;
       }
       m_ListMutex.release();

       return pConnectHandle;
}

//从使用队列中释放一个使用完毕的句柄,插入到空闲队列
void CDBManager::SetIdleConnectHandle(MYSQL * connecthandle)
{
       m_ListMutex.acquire();
       m_lsBusyList.remove(connecthandle);
       m_lsIdleList.push_back(connecthandle);
       m_ListMutex.release();
}
//使用示例,首先获取空闲句柄,利用这个句柄做真正的操作,然后再插回到空闲队列
bool CDBManager::DeleteHostCacheBySessionID(char * sessionid)
{
       MYSQL * pConnectHandle = GetIdleConnectHandle();
       if(!pConnectHandle)
              return 0;
       bool bRet = DeleteHostCacheBySessionID(pConnectHandle, sessionid);
       SetIdleConnectHandle(pConnectHandle);
       return bRet;
}
//传入空闲的句柄,做真正的删除操作
bool CDBManager::DeleteHostCacheBySessionID(MYSQL * connecthandle, char * sessionid)
{
       char deleteSQL[SQL_LENGTH];
       memset(deleteSQL, 0, sizeof(deleteSQL));
       sprintf(deleteSQL,"delete from HostCache where SessionID = '%s'", sessionid);
       if(mysql_query(connecthandle,deleteSQL) != 0) //删除
              return false;
       return true;
}

[!--infotagslink--]

相关文章

  • 全身个性化!贱驴619打滚机械键盘87键评测

    电竞行业的红火带动了机械键盘的发展,不少我们熟知的老牌PC厂商都纷纷进军了电竞行业。当然了免不了一些年轻的电竞厂商。贱驴就是在这个时代诞生的,旗下最让我们熟知的就是模块化的007电竞鼠标了!其他的电竞产品也人如其名,和贱驴的名字一样非常有个性化,本次评测的是贱驴619打滚机械键盘,驴打滚这种命名也真的是醉了,废话不多说先来开箱看看!...2016-09-12
  • 百度网盟和google网盟推广那种效果好

    专做了百度和google的网盟推广以作推广效果的评估比较。百度的周期为6天,google为4天。   从百度的统计数据可以看出这六天的点击次数总共为464,平均点击花费了0.30元...2017-07-06
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • python读取和保存mat文件的方法

    本文主要介绍了python读取和保存mat文件的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-08-25
  • python 实现将Numpy数组保存为图像

    今天小编就为大家分享一篇python 实现将Numpy数组保存为图像,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • 安卓开发之保存ImageView中的图片到本地相册

    下面我们来看一篇关于安卓开发之保存ImageView中的图片到本地相册教程吧,希望这篇教程能够给大家带来帮助. 代码如下. private void saveImage(ImageView imageVi...2016-11-01
  • C#抓取网络图片保存到本地的实现方法

    下面小编就为大家分享一篇C#抓取网络图片保存到本地的实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-25
  • Google会不会取消PR的理由分析

    Google是这样介绍PageRank的:   Google 出类拔萃的地方在于专注开发“完美的搜索引擎”,联合创始人拉里&middot;佩奇将这种搜索引擎定义为可“确解用户...2017-07-06
  • JS实现获取来自百度,Google,soso,sogou关键词的方法

    这篇文章主要介绍了JS实现获取来自百度,Google,soso,sogou关键词的方法,结合实例形式分析了js获取来路页面的方法与相关搜索引擎关键词的处理技巧,需要的朋友可以参考下...2017-01-09
  • 精华:GOOGLE搜索秘籍全攻略

    一,GOOGLE简介   Google(www.google.com)是一个搜索引擎,由两个斯坦福大学博士生Larry Page与Sergey Brin于1998年9月发明,Google Inc. 于1999年创立。2000年7月...2016-09-20
  • 怎么提高google adsense点击率

    本文章根据我们经验我们来说说怎么提高google adsense点击率吧。 本文章根据我们经验我们来说说怎么提高google adsense点击率吧。   第a步   接下来我们要安...2017-07-06
  • OpenCV获取视频的每一帧并保存为.jpg图片

    这篇文章主要为大家详细介绍了OpenCV获取视频的每一帧,并保存为.jpg图片,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-04-25
  • pytorch模型的保存和加载、checkpoint操作

    这篇文章主要介绍了pytorch模型的保存和加载、checkpoint操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-06-06
  • Google开源图形API调试工具GAPID,可跨平台使用

    Google 最近发布并开源了 GAPID,这是一个工具合集,允许检查、调整和重复从应用程序到 Graphics 驱动之间的调用。...2017-07-06
  • Python3中PyQt5简单实现文件打开及保存

    本文将结合实例代码,介绍Python3中PyQt5简单实现文件打开及保存,具有一定的参考价值,需要的朋友们下面随着小编来一起学习学习吧...2021-06-10
  • php读取和保存base64编码的图片内容

    这篇文章主要为大家详细介绍了php读取和保存base64编码的图片内容,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-04-26
  • 在网页上显示你Google Talk的在线状态

      一个英国人在自己的网站Jon Burrows上推出了一项服务:显示 Google Talk 的在线状态!   下面是先锋 JasonIT 的显示:   大家可以看见,显示有“GTAlk On-Lin...2016-09-20
  • php把txt文本转换成数组并保存数据库

    今天有一个工作要做就是把一个达5万条的记录的txt 文件的内容要保存到数据库,开始想到用file_get_contents后来就看到可以用file更简单,下面是我写的程序. <?php inc...2016-11-25
  • google PR劫持查询程序

    $fp = fsockopen("www.google.cn", 80, $errno, $errstr, 30); if(!$fp){ echo "$errstr ($errno)<br /> "; }else{ $out = "GET /search?oe=utf8&ie=utf8&sourc...2016-11-25
  • php 连接odbc数据源并保存 查询数据

    代码如下 复制代码 $connstr = "driver=microsoft access driver (*.mdb);dbq=".realpath("db.mdb"); $connid = odbc_connect($connstr,"",...2016-11-25