简体   繁体   English

将php返回值分配给javascript变量

[英]assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. 我在MySql表上有一个数据库表单,我有一个javascript函数来填充select标签的选项。 Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. 这些选项是从状态为“活动”或“非活动”的客户端表中获取的,返回值是那些状态为活动状态的客户端。 In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. 如果在客户端状态为非活动状态的情况下加载订单,我正在尝试为非活动客户端添加处理程序。 The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. 表单从一个php脚本加载,该脚本将客户端表连接到主表,其中主表中的clientId等于客户端表中的Id So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status. 因此,无论状态如何,我都会在函数外部获取客户端的名称和ID以填充选项列表。

There is one line that is causing me fits. 有一条线让我适应。 I have searched this site and others and have found many solutions, but none have worked for me so far. 我搜索了这个网站和其他人,并找到了很多解决方案,但到目前为止还没有一个对我有用。 This is the line: 这是一行:

var txt = <?php echo $row[`clients`.'name']; ?> ;

What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". Chrome和Firefox调试程序返回的内容是“未捕获的语法错误:意外的令牌<”。 The debugger shows: var txt = <br /> 调试器显示: var txt = <br />

I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. 我已经尝试用单引号,双引号和没有引号括起php脚本,但仍然没有运气。 Any thoughts, anyone? 任何想法,任何人?

About an hour later--> I found a workaround. 大约一个小时后 - >我找到了一个解决方法。 I tried all of your suggestions, but none worked in this instance. 我尝试了你的所有建议,但在这种情况下都没有。 var_dump and json_encode confirmed what I knew already, that the returned data was valid. var_dump和json_encode确认了我已经知道的,返回的数据是有效的。 Regardless of any of the variations in syntax, they all returned the same error. 无论语法有何变化,它们都返回相同的错误。 What I did was to apply the same syntax as above, but in a hidden input: 我所做的是应用与上面相同的语法,但在隐藏的输入中:

<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />

Then changed the javascript code to this: 然后将javascript代码更改为:

 var txt = document.getElementById('cName').value;

Everything else works perfectly. 其他一切都很完美。 Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. 当然,我仍然对使用反引号有一些挥之不去的想法,并希望我有一个更好,更安全的代码。 As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. 正如我在某处提到的,我只是直接从phpMyAdmin复制了sql语法。 In this instance, if I substitute single quotes for the backticks, the input returns nothing. 在这种情况下,如果我用反引号替换单引号,则输入不返回任何内容。 Well, thanks all. 好吧,谢谢大家。 If anyone wants to contribute more, I'll be glad to hear about it. 如果有人想贡献更多,我会很高兴听到它。

That's illegal PHP syntax, and very dangerous syntax in general. 这是非法的PHP语法,一般来说语法非常危险。 Try doing a var_dump($row) to see exactly what's in that array. 尝试执行var_dump($row)以查看该数组中的确切内容。 Probably you want something more like 可能你想要更像的东西

var txt = <?php echo json_encode($row['clients.name']); ?>;

instead. 代替。

Note the use of json_encode() . 注意使用json_encode() This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript. 这将确保无论你在JS代码块中吐出什么,实际上是语法上有效的javascript。

eg consider what'd happen if you ended up with 例如,考虑如果你最终会发生什么

var txt = Miles O'Brien;
          ^^^^^--undefined variable;
                ^--- another undefined var
                 ^--- start of a string
                  ^^^^^^^---unterminated string.

with json_encode(), you end up with 使用json_encode(),你最终得到了

var txt = "Miles O'Brien";

and everything's a-ok. 一切都很好。

Change this 改变这个

var txt = <?php echo $row['clients'.'name']; ?> ;

to this: 对此:

var txt = <?php echo $row['clients']['name']; ?> ;
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;

Consider how PHP parses this: 考虑PHP如何解析这个:

  1. var txt = is to be output directly to the client. var txt =将直接输出到客户端。

  2. Enter PHP mode. 进入PHP模式。

  3. echo the following expression. echo显以下表达式。

  4. Evaluate $row[`clients`.'name'] . 评估$row[`clients`.'name']

    • First we need to determine the array index, which is the concatenation of `clients` and 'name' . 首先,我们需要确定数组索引,它是`clients`'name'的串联。

    • Backtick in PHP is the execution operator , identical to shell_exec() . PHP中的反引号是执行运算符 ,与shell_exec()相同。 So PHP attempts to execute the shell command clients , which probably fails because that isn't what you intended and it doesn't exist. 因此,PHP尝试执行shell命令clients ,这可能会失败,因为这不是您的意图,也不存在。 Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br /> . 因此,在此阶段,PHP会输出HTML错误消息,从换行符开始<br />

    • Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. 您的客户端现在有var txt = <br /> (您可以通过检查返回到浏览器的页面的HTML源来验证这一点),它会尝试在其JavaScript上下文中进行评估。 This gives rise to the "unexpected token" error that you have witnessed. 这会导致您目睹的“意外令牌”错误。

As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. 正如其他人提到的那样,你可能想要做一些像$row['clients']['name']$row['clients.name'] - 但是没有看到PHP的其余部分,就不可能确定。 Also, as @MarcB has observed , you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value. 此外,正如@MarcB所观察到的 ,您需要确定结果输出是有效的JavaScript,并且可能希望使用类似json_encode()的函数来适当地转义该值。

The error comes from the fact that your return value (a string in javascript) must be in quotes. 该错误来自于您的返回值(javascript中的字符串)必须在引号中。

Single quotes will take whatever is between them literally, escapes (like \\n ) will not be interpreted, with double quotes they will. 单引号将从字面上取得它们之间的任何内容,不会解释转义(如\\ n),使用双引号。

var txt = "<?php echo $row['clients']['name']; ?>";

is what you want 是你想要的

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

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