Converting a variable url to a script in the header

Converting a variable url to a script in the header
0

#1

When I use Bootstrap and jQuery, I Google the CDN and then just add the link element to my head section. I am working in a local environment instead of CodePen. I am working on Quote Machine now. Here is my scripts file:

$(document).ready(function() {
  var api =
    "https://api.forismatic.com/api/1.0/?
    method=getQuote&lang=en&format=jsonp&jsonp=?";

  $("#generateQoute").on("click", function() {
    $.getJSON(api, function(json) {
      $("#quote").html(json.quoteText);
      $("#author").html("<cite>-- " + json.quoteAuthor + "</cite>");
    });
  });
});

Can I put that variable in the head section of my html file, so I don’t have to declare a variable inside my script and jQuery function? If I can, what would I replace inside my getJSON method for the URL parameter? Thanks for reading.


#2

If you are referring to the api string variable, then you could have a separate script file with global variable definitions and then you would need to link it into your html file. What is your reason for wanting to separate variable? It is totally possible, but seems unnecessary.

If you did not want a separate file to link in, then you could put the following in your html head section.

<head>
<script>
  var api = "https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?";
</script>
</head>

You would not have to modify your other code. Just make sure your load your main .js file containing the following somewhere after the above script (typically at bottom of <body>

$(document).ready(function() {
  $("#generateQoute").on("click", function() {
    $.getJSON(api, function(json) {
      $("#quote").html(json.quoteText);
      $("#author").html("<cite>-- " + json.quoteAuthor + "</cite>");
    });
  });
});

#3

Thanks for replying. I guess I phrased my question a little weird. When I imported jQuery and Bootstrap I used a CDN in a link tag.

<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-
      FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" 
      crossorigin="anonymous"></script>

<script type="text/javascript" src="scripts.js"></script>

Can I use the Forismatic API like this with just using a link tag that imports all the functionality?


#4

No, because an API is a functioning program on another server. When you import jQuery and Bootstrap, you are just importing code (text). They are not the same thing as a program which interacts with a server and returns data.


#5

Everything is clarified and now I understand. Thanks for your help @randelldawson