简体   繁体   中英

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. Whenever I try to do so I am getting the error of $ is not defined. This is the following code snippets.

HTML code:

<!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:

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.

separate.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

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM