从Perl调用Javascript函数

时间:2012-01-06 12:49:18

标签: javascript perl cgi

这应该很简单 - 不要弄错我做错了!这是一个非常基本的测试(我是PERL和Javascript的新手) - 这是CGI文件:

#! /usr/local/bin/perl

print "Content-type: text/html\n\n";
print "<html>\n" ;
print "<head>Hello\n";
print '<script type="text/javascript" language="javascript" src="wibble.js">\n';
print "</script>\n";
print "</head>\n";

print "<body>\n";

$fred = "Fred";
$numb = 7;

print <<TEST;

<p>Starting...</p>
<p><script type="text/javascript" language="javascript">
theText = "$fred";
theNum = "$numb";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);

testWrite(theNum, theText);

</script></p>

<p>...ending JS</p>

TEST

和wibble.js:

function testWrite(num1, txt1)
{
   document.writeln("In testWrite...");
   document.writeln("Number is: " + num1);
   document.writeln("Text is: " + txt1);
}

在我的浏览器中,我得到了第一组writeln,但我的函数从未调用过。网页上的错误在第15行('print <<TEST'行)显示“对象预期”。

我大多怀疑我在src元素中没有正确的路径,但我已经尝试了我能想到的每个组合('。','。/',完整路径等) - 没有任何作用。 js文件与CGI文件位于同一目录中。

(我实际上最初没有参数的函数调用,希望Num和theText是全局的并且仍然可以工作(这是该测试程序的原始点)。)

请把我从痛苦中解救出来......

根据要求,这是来自浏览器的源代码:

<html>
<head><script type="text/javascript" language="javascript" src="wibble.js"></script>
</head>
<body>

<p>Starting...</p>
<p><script type="text/javascript" language="javascript"> 
theText = "Fred";
theNum = "7";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);

testWrite(theNum, theText);

</script></p>

<p>...ending JS</p>

</body>
</html>

这是网页上的实际输出:

Starting...

Direct write... Number is: 7 Text is: Fred 

...ending JS

1 个答案:

答案 0 :(得分:3)

您是否检查过服务器的日志以查看是否曾要求使用wibble.js?如果不是,那就是你的问题。同样,虽然不是真正的问题,但这一行:

print "<head>Hello\n";

正在生成糟糕的HTML。您不能在<head>区块中包含“裸”文本。

对于全局JS变量,您使用var关键字。

x = 7; // local
var y = 7; // global
相关问题