简体   繁体   English

将带有双引号和单引号的字符串作为参数传递给javascript函数

[英]pass a string with double and single quotes as parameter to javascript function

Can anyone help me why this value from the database wont pass as a parameter 谁能帮我为什么数据库中的这个值不会作为参数传递

The value from the database has single and double quotes which i escaped using mysql_escape_string() before adding to the database. 来自数据库的值具有单引号和双引号,在添加到数据库之前,我使用mysql_escape_string()对其进行了转义。

<?php   
   $sample = "This is a test's \"output\".";
?>
<button onclick='myFunction(<?php echo addslashes($sample);?>)'></button>
<script>
 function myFunction(val){ 
    alert(val);
 }
</script>

Thanks guys! 多谢你们!

json_encode($s, JSON_HEX_TAG+JSON_HEX_APOS+JSON_HEX_QUOT)

Use like this way. 像这样使用。 Hope it will work. 希望它能工作。

<?php
    $sample = "This is a test's \"output\".";
    $sample = json_encode($sample);
?>
<button onclick="myFunction(<?php echo htmlentities($sample); ?>)">Button</button>

<script>
    function myFunction(val){
        alert(val);
    }
</script>

Use base64 encode. 使用base64编码。 You encode it in php, it wont have any quotes, and you can decode it in javascript, ie 您使用php对其进行编码,它不会包含任何引号,并且您可以使用javascript对其进行解码,即

<?php   
   $sample = "This is a test's \"output\".";
   echo base64_encode($sample);// VGhpcyBpcyBhIHRlc3QncyAib3V0cHV0Ii4=
?>

then 然后

console.log(atob("VGhpcyBpcyBhIHRlc3QncyAib3V0cHV0Ii4=")); // This is a test's "output".

so just: 所以就:

<button onclick="myFunction(atob(<?php echo base64_encode($sample); ?>))">Button</button>

Further reading: 进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

http://php.net/manual/en/function.base64-encode.php http://php.net/manual/zh/function.base64-encode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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