【问题标题】:Why can't I pass a string as a parameter in a Javascript function?为什么我不能在 Javascript 函数中将字符串作为参数传递?
【发布时间】:2013-01-23 05:18:12
【问题描述】:

我在 php 中有以下代码:

<?php
$apples = 123123;
echo "<td>
         <input type='button' onclick='confirmation($apples)' value='ac/in'>
      </td>";

echo('<script type="text/javascript">
           function confirmation(test) {
              var answer = confirm("Are you sure?")
              if (answer){
                  alert(test);
                  $.get("/index.php?f=func_name_to_call", 
                  {name: "John", hobby: "Programming"}, function(data) {});
              }
           }
</script>');
?>

如果 $apples 是一个数字,那么参数会正确传递;但是,当它是一个字符串时,函数确认()被破坏。有任何想法吗?提前致谢。

【问题讨论】:

  • 如果你发送一个字符串,它必须被这样对待。引用它。

标签: php javascript function arguments


【解决方案1】:

如果您希望它以字符串形式传递参数,请使用下面的编辑代码

echo "<td><input type='button' onclick='confirmation(\"$apples\")' value='ac/in'></td>";

只需使用\ 转义双引号,它就会被视为字符串。

【讨论】:

  • 或者,您可以使用json_encode($apples)。如果它是一个字符串,它将为您引用变量。以及让您将更复杂的数据结构(例如关联数组)传递给 javascript。
  • 它也会为你转义字符串。
【解决方案2】:

是的,你必须在调用确认函数时使用转义字符\“\”,因为你在一个不带双引号的整数类型参数中传递整数。因此它将字符串转换为整数...

【讨论】:

    【解决方案3】:
    <?php
    $apples = 123123;
    ?>
    <td>
        <input type='button' onclick='confirmation(<?php echo $apples?>)' value='ac/in'>
    </td>
    
    <script type="text/javascript">
        function confirmation(test) {
            var answer = confirm("Are you sure?")
            if (answer){
                alert(test);
                $.get("/index.php?f=func_name_to_call", 
                {name: "John", hobby: "Programming"}, function(data) {});
            }
        }
    </script>
    

    您将遇到将所有' 转换为" 的麻烦,因为您通过php 回应它们,只是建议不要echo 他们,使用html 标记并转义您的@ 987654327@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2023-03-16
      • 2021-10-10
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多