日期:2014-05-16  浏览次数:20278 次

js如何获取页面数据的自己数
一个form表单,里面好多要填写的东西,填好了之后,提交时用js验证一下提交数据的字节数总和,怎么做呢

------解决方案--------------------
如果都是输入框的话可以这样计算:

<input type="text" id="t1" />
<input type="text" id="t2" />
<input type="button" onclick="testBt()" />
<script type="text/javascript">
function testBt()
{
var allstr = '',count=0;
allstr+=document.getElementById('t1').value;
allstr+=document.getElementById('t2').value;
count = allstr.replace(/[^\x00-\xFF]/g,'**').length;
alert('表单中输入的文字一共占了'+count+'个字节');
return count;
}

</script>




------解决方案--------------------
关键是这句正则,算出字符串所占字节数 
[字符串].replace(/[^\x00-\xFF]/g,'**').length
------解决方案--------------------
探讨

如果都是输入框的话可以这样计算:

<input type="text" id="t1" />
<input type="text" id="t2" />
<input type="button" onclick="testBt()" />
<script type="text/javascript">
function testBt()
{
var allstr……

------解决方案--------------------
name 是留给服务器用的, js 以 id 为依据,有方法 getElementByName,不过 IE 下反正是有 bug 的。如果实在要以 name 为依据,遍历所有表单节点,判断 name 属性。至于说字节数,每个字符两个字节;上传文件的话 js 牵涉到权限问题,不借助第三方的东西(如插件)不能直接获取;服务器端的话,还要考虑 http 协议头的大小。