在 Jquery.val() funciton 中使用 vaable 时出错

Error while using valiable in Jquery.val() funciton

本文关键字:vaable 出错 funciton Jquery val      更新时间:2023-09-26

当我在 val() 函数中使用变量而不是固定值时,我没有输出。如何修复此错误。

示例:在下面的示例中,当我使用变量 ($data="Glenn Quagmire") 时,我没有得到任何输出。

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    <?php $data="Glenn Quagmire";  ?>
    $("input:text").val($data);
  });
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>

问候

只需像这样使用:

$("input:text").val("<?php echo $data; ?>");

完整代码

<script>
 $(document).ready(function(){
 $("button").click(function(){
 <?php $data="Glenn Quagmire";  ?>
 $("input:text").val("<?php echo $data; ?>");
 });
 });
</script>

不要在jQuery中使用"$"作为变量(即PHP)。

<?php echo 'data="Glenn Quagmire";';  ?>
$("input:text").val(data);

浏览器中运行的JavaScript无法访问PHP程序中的变量(在将页面交付给浏览器之前,PHP程序已经在另一台计算机上完成了运行,因此变量甚至不再存在)。

你必须让PHP将数据输出到JavaScript。

您可以使用json_encode对其进行编码(因为JSON(或多或少)是JavaScript文字语法的子集)。这将根据需要添加引号并转义数据中的任何特殊字符(您的示例中没有任何特殊字符,但这是一种安全的通用方法,可以保护您免受 XSS 的侵害)。

$("input:text").val(<?php echo json_encode($data); ?>);

使用 <?= $variable ?> 在 HTML 中嵌入变量值,例如:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        <?php $data="Glenn Quagmire";  ?>
        $("input:text").val("<?= $data ?>");
    });
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>