今天碰到一個問題,在要通過ajax實現分頁,需要對ajaxMethod返回的Html代碼端重新組裝,一段是分頁,另一段是查詢的結果,這樣問題就來,如何分離這兩端代碼?我想到的辦法就是在ajaxMethod裡構造一個javascript對象,把這兩段代碼加到對象的屬性值中如此模樣
“//construct javascript object
var objHTML = new Object();
objHTML.firstSection = ?;
objHTML.secondSection = ?;
"
然後在前台的callback函數中通過eval(strCode)構造返回的javascript對象,接下來更新相應的HTML塊就非常簡單啦。
在我替換上面代碼中的問號處,本來是換上兩段HTML代碼塊字串就可以啦,但我想如果在這裡給他們加上encode,那麼在前台如何decode呢,我試了在後台加上Server.URLEncode(strHtml),前台需要套uridecode()和unecape(),但裡面的空格還是‘+’,在加一個replace(/\+/g,' ')就可以搞定啦,這樣潛在的一個問題就是如果內容裡面本來就有'+'會有問題的,於是我在網上搜了一下看看有沒有更好的解決辦法,結果發現一種很巧的辦法,用HTML中的容器來實現。
javascript HTMLencode實現:function HTMLEncode(strHTML)
{
var div = document.createElement('div');
div.innerText = strHTML;
return div.innerHTML;
}
javascript HTMLdecode實現:function HTMLDecode(strEncodeHTML)
{
var div = document.createElement('div');
div.innerHTML = strEncodeHTML;
return div.innerText;
}
這樣實現很方便簡單,下面是範例程式碼供參考<script type="text/javascript">
function HTMLEncode(strHTML)
{
var div = document.createElement('div');
div.innerText = strHTML;
return div.innerHTML;
}
function HTMLDecode(strEncodeHTML)
{
var div = document.createElement('div');
div.innerHTML = strEncodeHTML;
return div.innerText;
}
function test1()
{
var strInput = prompt('test HTMLEncode(),please input decodeHTML','<div style=\"width:600px;\"><input type=\"button\" name=\"runStart\" value=\"View\" onclick=\"Run()\" style=\"margin-left:2px;\" /><input type=\"button\" name=\"runStart\" value=\"RunScript\" onclick=\"RunScript()\" style=\"margin-left:10px;\" /><input type=\"button\" name=\"reset\" value=\"Clear\" onclick=\"Reset()\" style=\"margin-left:18px;\" /><span onclick=\"ExpandCollapse(this);\" onmouseover=\"showMsg();\" onmouseout=\"hideMsg();\" msg=\"expand\" style=\"font-family:webdings;font-size:18pt;cursor:pointer;\">5</span></div><iframe name=\"ifrShow\" style=\"margin:0px;margin:0px;width:600px;height:400px;border:1px orange solid;\"></iframe><div id=\"divMsg\" style=\"display:none\"></div>');
alert(HTMLEncode(strInput));
}
function test2()
{
var strInput=prompt('test HTMLDecode(),please input encodeHTML','<div style="width:600px;"><input type="button" name="runStart" value="View" onclick="Run()" style="margin-left:2px;"><input type="button" name="runStart" value="RunScript" onclick="RunScript()" style="margin-left:10px;"><input type="button" name="reset" value="Clear" onclick="Reset()" style="margin-left:18px;"><span onclick="ExpandCollapse(this);" onmouseover="showMsg();" onmouseout="hideMsg();" msg="expand" style="font-family:webdings;font-size:18pt;cursor:pointer;">5</span></div><iframe name="ifrShow" style="margin:0px;margin:0px;width:600px;height:400px;border:1px orange solid;"></iframe><div id="divMsg" style="display:none"></div>');
alert(HTMLDecode(strInput));
}
</script><button onclick="test1();">test HTMLEncode</button>
<button onclick="test2();">test HTMLDecode</button>