简体   繁体   中英

escape characters with javascript

I have a function that opens up a browser window:

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open("mydir/file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+cameraname+"&quality="+cameraflashquality+"&motion="+cameramotion, "Webcam_monitor");
}

cameraname is passed in from a button in html:

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', '<?php echo $result_cameras[$i]["camera_name"]; ?>', '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

cameraname does take special characters. Such as Al's camera . Because of the special character it messes up the window.open line. Anyone have ideas how I can rewrite the window.open line to accommodate this?

You might try encodeUri

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open(encodeUri("file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+cameraname+"&quality="+cameraflashquality+"&motion="+cameramotion), "Webcam_monitor");
}

Edit: Actually, because you are wanting to encode the apostrophe, you would need to use the escape function around the variables you wish to escape. In this case it would be used around the cameraname variable.

function startmonitor(camerahash, cameraname, cameraflashquality, cameramotion)
{
    window.open("file.php?user="+'<?php echo $id_hash; ?>'+"&camera="+camerahash+"&name="+escape(cameraname)+"&quality="+cameraflashquality+"&motion="+cameramotion, "Webcam_monitor");
}

Edit 2 OK, it looks like, based on your comment below, that you need to escape cameraname before it enters your startmonitor function. So you would actually escape it in your button code and not in your function code.

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', escape('<?php echo $result_cameras[$i]["camera_name"]; ?>'), '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

Edit 3 Wow - I'm retarded. Just encode with php's urlencode function before outputting to the page.

<button id="monitor" onclick="startmonitor('<?php echo $result_cameras[$i]["camera_hash"]; ?>', <?php echo urlencode($result_cameras[$i]["camera_name"]); ?>, '<?php echo $camera_quality_flash; ?>', '<?php echo $camera_motion; ?>');">Start Camera</button>

有3种转义特殊字符的方法:

  • escape()
  • encodeURI()
  • encodeURIComponent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM