微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – MD5字符串无法正确显示html()

我有两个带有盐和密码的跨度

<div>
    $salt = '<span id="salt"></span>';<br />
    $password = '<span id="password"></span>';
</div>

然后我使用以下jQuery代码获取salt,将其添加用户输入的密码,并返回salt和散列密码(以复制到配置文件中)

salt = (Math.random() +1).toString(36).substr(2,16);
$('#salt').html(salt);
hashed = CryptoJS.MD5(salt + $(this).val());
$('#password').html(hashed);

代码使用salt ID将salt添加到span中,但它不会向密码ID添加任何内容.

如果我输入代码警报(哈希),它将打开一个md5值的警报.

如果我将.html()更改为.text(),它就可以了.

解决方法

CryptoJS.MD5()方法返回一个对象.要将此对象转换为字符串,请使用toString()方法.

hashed = CryptoJS.MD5(value);
var hashedString = hashed.toString();

而不是将文本插入元素使用jQuerys text()方法. jQuery html()方法用于设置元素innerHTML值.但是你想插入未转义的文字.

$('#password').text(hashedString);

如果一个对象传递给text(),它将自动调用它上面的toString(),尽管引用中没有记录

参考

.text(文字)

The text to set as the content of each matched element. When Number or Boolean is supplied,it will be converted to a String representation. […] be aware that this method escapes the string provided as necessary so that it will render correctly in HTML.

jQuery API Documentation: text()

.html(htmlString)

A string of HTML to set as the content of each matched element

jQuery API Documentation: html()开始

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐