这应该很简单 - 不要理解我做错了什么!这是一个非常基本的测试(我是 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 文件位于同一目录中。
(实际上我最初有不带参数的函数调用,希望 theNum 和 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
最佳答案
您是否检查过服务器日志以查看是否曾经请求过 wibble.js?如果不是,那就是你的问题了。同样,虽然这不是真正的问题,但这一行:
print "<head>Hello\n";
正在生成错误的 html。 <head>
中不能有“裸”文本 block 。
对于全局 JS 变量,您可以使用 var
关键字。
x = 7; // local
var y = 7; // global
关于javascript - 从 Perl 调用 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758038/