<script type="text/javascript">
function htmlEncode (str){
var div = document.createElement("div");
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
function htmlDecode (str){
var div = document.createElement("div");
div.innerHTML = str;
return div.innerHTML;
}
</script>
功能同函数名,htmlEncode是让document.createTextNode把html代码转换成文本了,而htmlDecode是通过设置div的innerHTML使得浏览器对文本(编码后的html)做了代码自动调整,还原成了html,从而实现了编码/解码功能。
这个方法在IE Firefox Opera上面均测试成功,别的浏览器应该也不会有多大问题。
PS:这个思路参考了
Javascript HtmlEncode/HtmlDecode
2007年4月16日星期一
用Javascript实现HtmlEncode与HtmlDecode的另类方法
Html的Encode和Decode在服务器端是很容易实现的,就拿ASP.net来说,调用现成的函数System.Web.HttpContext.Server.HtmlEncode或HtmlDecode就能简单了事。
但随着Ajax的发展,人们越来越重视javascript或vbscript的编程,这就使得大家不得不用这些脚本语言解决一些曾经不长解决的问题,Html的Encode / Decode就是一个这样的例子,javascript好像并没有现成的函数,网上的相关代码也很少,主要思想大都是用正则表达式来替换(replace)"<"、">"、"&"等符号,其实有一个很巧妙的办法能解决这个问题,请看下面两个函数
强制Opera刷新页面(Ajax)
用Opera测试我的基于Ajax的聊天程序的时候发现总是接收到相同的数据,而Mozilla Firefox和Internet Explorer却能正常接收到时时更新的数据,这显然是xmlhttp使用Opera的缓存造成的。我试着将服务器端的Response.Expires设成-1问题就解决了。
后来从网上看到
<% '强制性刷新随机验证码 '让随机验证码每次按IE的后退按钮时,返回登录页面的随即码都自动刷新, Response.expires=-1 Response.AddHeader"pragma","no-cache" Response.AddHeader"cache-control","no-store" %>这应该是更完善的解决方案(ASP的)
2007年4月14日星期六
我惯用的解决Ajax中文乱码问题的手段
这个问题又被人叫做xmlhttp中文乱码问题,网上有很多种解决的方法,虽然能解决问题,但是代码量不小。我从来不认为这东西有那么费尽,很简单,在服务器端“Response.Charset = "utf-8";”在客户端把要post或者get过去的中文用javascript的“escape("中文");”编一下码就都解决了。
appendChild() invalid for frame?
See http://lists.evolt.org/archive/Week-of-Mon-20030616/143280.html
In trying to use the DOM to perform some acrobatics for a CMS, using
cloneNode() and appendNode() to try to copy some default XHTML into a
IFRAME:
<html> <body onload="initFrame()">
<div id="foo" style="display: none">this is some <em>foo</em> for you</div>
<iframe id="theFrame" width="310" height="100"></iframe>
<script>
function initFrame() {
var newNodes = document.getElementById('foo').cloneNode(true);
newNodes.style.display = 'block';
var idoc =
document.getElementById('theFrame').contentWindow.document;
idoc.body.appendChild(newNodes);
}
</script>
</body></html>
This works fine in Mozilla. IE6 says "Invalid Argument" at the
appendChild()
line. Have tried many permutations of replaceChild(), insertBefore(), etc.
with the same result. It does work if the node I am appending to is in the
same document (not in a separate frame)...
I got the same problem.
Until now the only key I found is to change "innerHTML" of the iframe.
Some one said:
You´re accessing the iframe incorrectly. Try frames[´theFrame´].document instead. See http://www.xs4all.nl/~ppk/js/index.html?iframe.html for more information.By using "frames[´theFrame´].document" I got the same result, It's also invalid.
订阅:
评论 (Atom)