在运行时添加js文件时出现语法错误

Syntax error when adding js file in runtime

本文关键字:语法 错误 文件 运行时 添加 js      更新时间:2024-04-22

所以我试图在运行时添加一个js文件,我有这个简单的HTML

<!doctype html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script src="jquery.js" type="text/javascript" ></script>
    <script src="main.js" type="text/javascript"></script>
</head>
<body onLoad="init();">
</body>
</hmtl>

在主要功能中,我有这个

function init() {
    $.getScript("bots/test.js");
}

我在test.js的第一行中得到一个语法错误,它包含了这个函数

function hello(){
    console.log("hello");
}

但问题是,如果我在确保加载了test.js文件后调用main.js中的hello函数,它就会正常工作。那么,为什么会出现语法错误呢?

如果我在html中包含test.js,那么也不会出现错误。

注意:错误消息不会阻止我所能告诉的一切仍然有效。

编辑:铬下的错误消息:

XMLHttpRequest cannot load file:///G:/tt/Desktop/black%20box/bots/test.js?_=1424695256510. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

为了回答一些问题,我使用按钮上的点击事件来调用"hello()"函数,该函数运行良好(在控制台中输出hello,不会出现任何错误)。

XMLHttpRequest无法加载file:///G:/tt/Desktop/black%20box/bots/test.js?_=1424695256510.跨源请求仅支持以下协议方案:http、data、chrome、chrome扩展、https、chrome资源扩展。

getScript通过Ajax加载文件。您不能对本地文件执行Ajax。在网络服务器上进行测试。

$.getScript使用ajax异步检索文件,然后执行它,它定义了一个hello函数,但没有调用它。您可以在$.getScript成功处理程序中调用该函数:

$.getScript('bots/test.js', function () {
    hello();
});

也许您应该在<head>之前添加一个<html>标记?