如何将Perl变量传递给Javascript函数?(How to pass Perl variable into Javascript function?)

编程入门 行业动态 更新时间:2024-10-24 10:20:59
如何将Perl变量传递给Javascript函数?(How to pass Perl variable into Javascript function?)

我有一个打印出html页面的Perl脚本。 我想使用javascript来弹出警报消息。 警报消息在perl变量中定义为字符串。 我试图将perl变量值传递给javascript函数作为参数,但它不起作用。 请帮忙。

$perl_variable = "Welcome"; # alert msg print <<START <HTML> some html code.... <p>Click the button to wait 3 seconds, then alert "Hello".</p> <button onclick="myFunction('$perl_variable')">Try it</button> <script> function myFunction(var message){ setTimeout(function(){alert(message)},3000); } </script> </HTML> START

I have a Perl script which prints out of html page. I want to use javascript to pop alert msg. The alert message is defined as string in the perl variable. I am trying to pass the perl variable value to javascript function as argument but it's not working. Please help.

$perl_variable = "Welcome"; # alert msg print <<START <HTML> some html code.... <p>Click the button to wait 3 seconds, then alert "Hello".</p> <button onclick="myFunction('$perl_variable')">Try it</button> <script> function myFunction(var message){ setTimeout(function(){alert(message)},3000); } </script> </HTML> START

最满意答案

注意:这个答案的前半部分是指最初(编辑之前)出现在问题中的代码。

你需要:

使用正确的变量名称 生成JavaScript字符串文字(通过引用数据)

这样:

myFunction('$perl_variable')

请注意,如果您的数据可能包含JavaScript字符串文字中不允许的字符(例如新行),则字符串文字中具有特殊含义的字符(例如分隔它的引号)或具有特殊含义的字符在HTML中(例如分隔属性值的引号),您还需要执行适当的转义(分两步,首先是JS,然后是HTML)。


作为旁白, 你在JS中的函数定义也是错误的:

function myFunction(var path){

var关键字可能不在FormalParameterList中使用。 那应该是:

function myFunction(path){

NB: The first half of this answer refers to the code that originally (before edits) appeared in the question.

You need to:

Use the right variable name Generate a JavaScript string literal (by quoting the data)

Such:

myFunction('$perl_variable')

Note that if your data might include characters that are not allowed in a JavaScript string literal (such as a new line), characters that have special meaning in a string literal (such as the quote mark that delimits it) or characters that have special meaning in HTML (such as the quote mark that delimits the attribute value) then you will also need to perform suitable escaping (in two steps, first for JS, then for HTML).


As an aside, your function definition in JS is also wrong:

function myFunction(var path){

The var keyword may not be used in the FormalParameterList. That should read:

function myFunction(path){

更多推荐

本文发布于:2023-08-04 14:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   函数   Perl   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!