javascript中的自訂屬性的應用–避免頻繁訪問資料庫

來源:互聯網
上載者:User

在WEB應用程式中,經常需要將資料從資料庫中取出來,填充到HTML控制項中,然後再存回資料庫。

如果資料並未改動,仍然佔用網路資源存入資料庫,則對網路資源是一種浪費,當頁面資料很多和網路訪問量很大時,就會形成效能的瓶頸。如何能在提交資料前進行判斷呢?

一種方法是建隱藏控制項或定義全域變數,這種情況適用於控制項很少時,若一個表單頁面有數十項時,建隱藏控制項太多反而降低效能,定義全域變數不容易記憶。

另一種方法,就是在原有控制項中增加自訂屬性,這樣,既能避免邏輯複雜,又能節省網路流量。

如頁面中有一文字框:

<input type="text" id="txtName">


在頁面的onload事件中加入如下代碼:

function initvalue()
{
        var xm = "張三";                //假設從資料庫中取得
    var obj = document.getElementById("txtName");
    obj.value = xm;
    obj.setAttribute("originValue",xm);
}

頁面添加一按鈕,其點擊事件onclick如下:function upload()
{
    var obj = document.getElementById("txtName");
    var xm = obj.value;
    var origin_xm = getCustomAttributeValue(obj,"originValue");
    if(xm == origin_xm)
    {
        alert("值未變,不需存回資料庫");
    }
    else
    {
            alert("值已發生改變,可以寫回! 初始值為:" + origin_xm + " 當前值為:" + xm);
            //寫回資料庫...
            //...
    }
}

代碼如下:<html>
<head>
    <title>自訂屬性應用</title>
    <script language="javascript">
        function initvalue()
        {
            var xm = "張三";                //假設從資料庫中取得
            var obj = document.getElementById("txtName");
            obj.value = xm;
            obj.setAttribute("originValue",xm);
        }
        
        function upload()
        {
            var obj = document.getElementById("txtName");
            var xm = obj.value;
            var origin_xm = getCustomAttributeValue(obj,"originValue");
            if(xm == origin_xm)
            {
                alert("值未變,不需存回資料庫");
            }
            else
            {
                    alert("值已發生改變,可以寫回! 初始值為:" + origin_xm + " 當前值為:" + xm);
                    //寫回資料庫...
                    //...
            }
        }
        
        function getCustomAttributeValue(obj,attr)
        {
            if(obj.attributes[attr])
                return obj.attributes[attr].nodeValue;
            else
                return null;
        }
        
        
        function setCustomAttributeValue(obj,attr,value)
        {
            if(value != null)
            {
                obj.attributes[attr].nodeValue = value;
            }
        }
    </script>
</head>
<body onload="initvalue();">
    <input type="text" id="txtName">
    <input type="button" value="存回資料庫" onclick="upload();">
</body>
</html>

原始碼:http://files.cnblogs.com/redleaf1995/jsSaveDB.rar

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.