简体   繁体   English

使用 php 变量设置输入值

[英]set value of input with php variable

Im trying to do something really simple I know I should probably be using ajax but I'm just doing some quick tests.我正在尝试做一些非常简单的事情,我知道我可能应该使用 ajax,但我只是在做一些快速测试。

so I have a display.php file with some variable and I want to display the PHP variable in the input text by using document.getElementbyID.value = myVariable所以我有一个带有一些变量的 display.php 文件,我想通过使用document.getElementbyID.value = myVariable在输入文本中显示 PHP 变量

//PHP
<?php
$name = 'Patrick';
?>

//HTML
First Name: <input type="text" id = "fname" name="fname" value=""   >

//JS
<script type="text/javascript">
     var f = <?php echo($name); ?>;
    document.getElementById("fname").value = f;`
</script>

I keep getting the error Uncaught ReferenceError: Patrick is not defined Not really sure whats wrong with my code it looks pretty simple but it don't want to put the value "Patrick" in the input box.我不断收到错误Uncaught ReferenceError: Patrick is not defined不太确定我的代码出了什么问题它看起来很简单但它不想在输入框中输入值“Patrick”。

Tried different ways of writing it with '' or using json_encode but didnt change anything still getting same error.尝试了用 '' 或使用 json_encode 编写它的不同方式,但没有改变任何仍然得到相同错误的东西。

Uncaught ReferenceError: Patrick is not defined未捕获的 ReferenceError:Patrick 未定义

That's because the resulting javascript is:那是因为生成的 javascript 是:

var f = Patrick;

Which means set f to the contents of the variable Patrick .这意味着将f设置为变量Patrick的内容。

Since there is no variable defined that is named Patrick you'll get the uncaught reference error.由于没有定义名为Patrick的变量,您将得到未捕获的引用错误。

You need to put Patrick in quotes like so:你需要像这样把帕特里克放在引号中:

var f = "Patrick"; // <-- Note the "

Note, since you want to pass data from PHP to JavaScript, a better way would be to use JSON like this:请注意,由于您要将数据从 PHP 传递到 JavaScript,因此更好的方法是像这样使用 JSON:

var f = <?php echo json_encode((string)$data); ?>;

This allows you to pass more complex types of data¹ AND you'll get proper escaped strings.这允许您传递更复杂类型的数据¹,并且您将获得正确的转义字符串。

Proper escaped strings?正确的转义字符串? If the user input is Test " (note the double quote) a primitive approach will break because the resulting javascript will be:如果用户输入是Test " (注意双引号),原始方法将失效,因为生成的 javascript 将是:

var f = "Test "";

This is not only a bug, but a security issue since user input could contain arbitrary javascript that would get executed.这不仅是一个错误,而且是一个安全问题,因为用户输入可能包含将被执行的任意 javascript。

¹ just remove the (string) cast. ¹只需删除(string)演员表。

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

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