为什么我不能在Javascript函数中传递字符串作为参数?

unw*_*guy 2 javascript php arguments function

我在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>');
?>
Run Code Online (Sandbox Code Playgroud)

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

Yog*_*har 7

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

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

只是\用于转义双引号,它将被视为一个字符串.

  • 或者,您可以使用`json_encode($ apples)`.如果它是一个字符串,它会为你引用变量.同时让您将更复杂的数据结构(如关联数组)传递给javascript. (5认同)