如何在JavaScript中正确转义JavaScript? [英] How can I properly escape JavaScript in JavaScript?

查看:123
本文介绍了如何在JavaScript中正确转义JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是我不能做的,但是...

  parent.document.getElementById('<? php echo $ _GET ['song'];?>')
.innerHTML ='< img src =heart.pngonmouseover =heartOver(''); >;

onmouseover =heartOver(''); 部分打破了我的JavaScript,有没有办法逃避引号,所以我可以这样做?

解决方案

反斜杠: \'



此外,永不回显用户数据,无需验证或消毒:

  $ song = $ _GET ['song']; 

//验证HTML id(http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/ ^ [az] [ - a-z0-9_:\\ \\ $] $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b

  // Sanitize 
$ song = preg_replace('/(^ [^ az] * | [^ - a-z0-9_:\。])/','',$ song);


This might be something I can't do but...

parent.document.getElementById('<?php echo $_GET['song']; ?>')
  .innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';

The onmouseover="heartOver(''); portion breaks my JavaScript. Is there a way to escape the quotes so I can do this?

解决方案

Escape nested quotes with a backslash: \'

Also, never echo user data without validating or sanitizing it:

$song = $_GET['song'];

// Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
    // Display error because $song is invalid
}

OR

// Sanitize
$song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);

这篇关于如何在JavaScript中正确转义JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆