如何修复 "EJS unable to access DOM causing Document is not Defined "

How to fix "EJS unable to access DOM causing Document is not Defined "

我正在使用 HTML5 中内置的地理定位 API,但主要问题是,我想将地理定位 Api 的结果存储在我的数据库中,以便继续那,我正在通过控制台打印结果但什么也没发生(事实上,我得到的文档未定义)。我也尝试过 window ,仍然是相同的响应。其次,当我 运行 以下 ejs 格式的代码删除脚本标签时,我得到 "document is not defined".

我还选择了另一种替代方法来解决此问题,我创建了一个空表单并通过脚本标签插入了两个输入隐藏标签并通过使用按 ID 选择标签并简单地更改它的值将我的结果存储在其中到我想要的结果。但是我的后端文件中出现空字符串。

(请只用JS回答)

我是 NodeJs 的新手,在发布这个问题之前我搜索了很多,没有得到所需的答案。非常感谢您花宝贵的时间来解决这个问题。

<!DOCTYPE html>
<html>
<body>

<p> coordinate of your current location</p>

<p id="demo"></p>

   <% var x = document.getElementById("demo");%> 
   <%   if (navigator.geolocation) { %>
   <%     navigator.geolocation.getCurrentPosition(function(position){  %> 
   <%         x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;%> 
   <%         console.log(position);  %> 
   // Not able to print the position on the console but prints results on browser perfectly
   <%     }); %> 
   <%   } else  %> 
   <%         x.innerHTML = "Geolocation is not supported by this browser.";%> 

</body>
</html>

我在我的浏览器中得到了理想的结果,但无法在控制台上打印结果。(使用脚本标记)否则我通过使用 ejs 格式

得到 "Document is not Defined"

<% %> 之间的任何代码都在 页面上的任何元素加载之前执行。

当这一行:

<% var x = document.getElementById("demo");%>

已处理,demo 元素尚不存在,这就是它 returns 未定义的原因。

您可以通过将此代码放入 <script> 标记来解决此问题:

<script type="text/javascript"> 
var x = document.getElementById('demo') //make sure this tag is below "demo"

if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position){   
          x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; 
          console.log(position); //client side JS will never print to your terminal.  It only prints to the browser.
        }); 
      } else   
            x.innerHTML = "Geolocation is not supported by this browser.";

</script>

或者,我建议将所有 JS 代码存储在另一个页面上并在底部链接。

yourFile.js:

(function() {
    var x = document.findElementById('demo');
    ...
)}();

然后在您的 ejs 模板上://在页面底部

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

此外,要使用此方法,您需要在应用程序的根目录中设置一个 public 目录,然后在您的 app.js 页面上执行此操作:

app.use(express.static('public'));

最后,我强烈建议学习 jQuery 和 Node.js

如果你已经了解JS,那么学习起来非常简单,因为它所做的只是为事件监听器提供快捷方式。

JS/jQuery 比较:

而不是 document.getElementById('id') 你只需写 $('#id')

而不是 document.querySelector('demo').innerHTML 你会写 $('#demo').html();

您需要做的就是将其放在代码底部(但在 JS 文件上方):

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

您可以了解更多 jQuery here

编辑

如果您需要在您的服务器上访问这些信息,您可以通过多种方式进行。在开始之前,请确保您已安装 body-parser,否则您将无法读取服务器上的 POST 请求。

正文解析器设置:

npm install body-parser

app.js:

const bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

yourFile.html:

<form action="/location" method="POST">
    <input type="hidden" name="lat"  id="lat">
    <input type="hidden" name="long" id="long">
    <input type="hidden" name="test" id="test">
    <button id="submit_button"></button> //a button's default type = "submit"

    //you can also use a submit input like this
    <input type="submit" id="submit_button">
</form>

yourFile.js:

(function() {

    //this sets the inputs when the page loads if navigator.geolocation isn't undefined
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        document.getElementById('lat').value = position.coords.latitude;
        document.getElementById('long').value = position.coords.longitude;
      });
    } else {
      //this is to prevent the form from submitting if navigator was unsuccessful in getting location data
      //also this method uses jQuery because I don't know how to do this with JS

      $('#submit_button').on('click', function() {
        event.preventDefault(); //this replaces the 'event' (ie form submit) with whatever code is in this function

        //do something here
        alert("Geolocation is not supported by this browser.");
      });
    }

})();

app.js:

这是您处理实际 POST 请求的地方。单击表单按钮时,您的服务器将收到带有路由 /location 的 HTTP POST 请求,因为表单的 action="/location"(在我的版本中)

app.post('/location', function(req, res) {
    console.log(req.body); 
    //this will print a JSON object with the values of all the inputs in the form
    res.render( ... handle the response here );
});

附带说明一下,如果您或任何人正在寻找好的 class 来开始学习开发,请尝试 this Udemy 课程。它的成本约为 12 美元,但如果您刚开始,这是值得的。

注意:你买那个课程我不赚任何钱,我也不认识老师。我推荐它是因为它对我有帮助。

注意: 永远不要为 Udemy 上的课程支付超过 15 美元!!!如果他们想向您收取超过 15 美元的费用,请执行以下操作:

  • 注销 Udemy
  • 清除浏览器缓存和 cookies
  • 更改您的 IP 地址(您可以使用 VPN,或者去朋友家)
  • 创建一个新的 email/Udemy 帐户,所有价格都会为您降价