[英]How to make an ajax call from a separate JS file
This is a working code.这是一个工作代码。 I just want to make the call from a separate js file.
我只想从一个单独的 js 文件进行调用。 Whenever I try to do so I am getting the error of $ is not defined.
每当我尝试这样做时,我都会收到 $ is not defined 的错误。 This is the following code snippets.
这是以下代码片段。
HTML code: HTML 代码:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script>
var data;
$.ajax({
headers: { 'X-Auth-Token': 'my API key' },
url: 'https://api.football-data.org/v2/competitions',
dataType: 'json',
type: 'GET',
}).done(function(response) {
// do something with the response
console.log(response);
data = response;
});
</script>
</body>
</html>
JS code: JS代码:
var express = require('express');
var app = express();
var hbs = require('hbs');
app.set('view-engine', 'hbs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.hbs');
})
app.listen(3000);
put you code inside of a function in the separate JS file.将代码放在单独的 JS 文件中的 function 中。
separate.js分离.js
function ajaxCall() {
var data;
$.ajax({
headers: { 'X-Auth-Token': 'my API key' },
url: 'https://api.football-data.org/v2/competitions',
dataType: 'json',
type: 'GET',
}).done(function(response) {
// do something with the response
console.log(response);
data = response;
});
}
then... in you html call the function然后...在您 html 中拨打 function
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="separate.js"></script>
...... more code .....
<script>ajaxCall()</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.