简体   繁体   中英

Using Javascript functions in a separate HTML file

I know it might seem like a dumb question but even with all the examples i have looked through i can not get it too work. I have the following code in my Javascript file

server.js

  // Google Maps Locaton 
  googleMapsClient.geocode({
    address: city
  }, function(err, response) {
    if (!err) {
      basicLocation = response.json.results[0].formatted_address;
      console.log(basicLocation);
    }
  });

});

function getBasicLocation() {   // Able to grab location from index.ejs file 
  return basicLocation;
}

in my HTML im trying to update text as the location changes. My html code looks like this

index.ejs

<script src="../server.js">
    </script>
      <h3>
        <script> getBasicLocation() </script> Location
      </h3>

The way my files are set up in the directory is like

- app 
   - views 
     - index.ejs
   - server.js

How do i get the getBasicLocation() to talk to my index.ejs file so that it updates the text?

Below steps should work -

  1. Import server.js - You are doing this
  2. create HTML node where you want location eg div id="location"
  3. create script tag with below content

      let lc = getBasicLocation(); document.getElementById("location").innerHTML = lc; 

JQuery can further simplify your node selection code

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