简体   繁体   English

如何修复“EJS 无法访问 DOM 导致文档未定义”

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

I am using Geolocation API inbuilt in HTML5 ,But the main problem is that,I want to store result from the geolocation Api in my db, Inorder to proceed over that ,I am Printing the result over console but nothing happened (In fact , I am getting document is not defined).I have also tried window too ,Still same response.我正在使用 HTML5 中内置的地理定位 API,但主要问题是,我想将地理定位 Api 的结果存储在我的数据库中,为了继续进行,我正在通过控制台打印结果但什么也没发生(事实上,我正在获取文档未定义)。我也尝试过窗口,仍然是相同的响应。 Secondly ,when I am running the below code in ejs format on removing script tag, I am getting "document is not defined".其次,当我在删除脚本标签时以 ejs 格式运行以下代码时,我收到“文档未定义”。

I have also choose another alternative method to resolve this issue , I made a empty form and through script tag I have inserted two input hidden tag and stores my result in it by using selecting tag by ID and simply change it's value to my desired result.我还选择了另一种替代方法来解决此问题,我创建了一个空表单,并通过脚本标签插入了两个输入隐藏标签,并通过使用按 ID 选择标签将结果存储在其中,只需将其值更改为我想要的结果。 But I am getting empty string in my backend file.但是我的后端文件中出现空字符串。

(Please give me answer in JS only ) (请只用 JS 给我答案)

I am new to NodeJs, I searched a lot before posting this question, didn't get the required answer.我是 NodeJs 的新手,在发布这个问题之前我搜索了很多,没有得到所需的答案。 I really appreciate your precious time for solving this queries.我非常感谢您解决此查询的宝贵时间。

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

I am getting desirable result in my browser but not able to print result on console.(USING SCRIPT TAG) otherwise I am getting "Document is not Defined" by using ejs format我在浏览器中获得了理想的结果,但无法在控制台上打印结果。(使用脚本标签)否则我将使用 ejs 格式获得“未定义文档”

Any code that is between <% %> is executed before any elements on the page load. <% %>之间的任何代码都在页面上的任何元素加载之前执行。

When this line:当这一行:

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

is processed, the demo element doesn't exist yet, which is why it returns undefined.已处理, demo元素尚不存在,这就是它返回 undefined 的原因。

You can fix this by putting this code in a <script> tag:您可以通过将此代码放在<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>

Or, what I would recommend is storing all your JS code on another page and linking at the bottom.或者,我建议将所有 JS 代码存储在另一个页面上并在底部链接。

yourFile.js:你的文件.js:

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

Then on your ejs template: //at the bottom of the page然后在你的 ejs 模板上://在页面底部

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

Also, to use this method, you need to setup a public directory in the root of your application, then do this on your app.js page:此外,要使用此方法,您需要在应用程序的根目录中设置一个public目录,然后在您的app.js页面上执行此操作:

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

Lastly, I would strongly recommend learning jQuery alongside Node.js最后,我强烈建议在 Node.js 的同时学习 jQuery

It is extremely simple to learn if you already know JS because all it does is provide shortcuts for event listeners.如果您已经了解 JS,那么学习它非常简单,因为它所做的只是为事件侦听器提供快捷方式。

JS/jQuery comparisons: JS/jQuery 比较:

instead of document.getElementById('id') you would simply write $('#id')而不是document.getElementById('id')你只需写$('#id')

instead of document.querySelector('demo').innerHTML you would write $('#demo').html();而不是document.querySelector('demo').innerHTML你会写$('#demo').html();

All you need to do is put this at the bottom of your code (but above your JS files):您需要做的就是将其放在代码的底部(但在 JS 文件上方):

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

You can learn more about jQuery here .您可以在此处了解有关 jQuery 的更多信息。

Edit编辑

If you need to access this information on your server, there are several ways you can do this.如果您需要在您的服务器上访问此信息,您可以通过多种方式执行此操作。 Before starting, make sure you have body-parser installed, or you won't be able to read the POST requests on your server.在开始之前,请确保您已安装body-parser ,否则您将无法读取服务器上的 POST 请求。

body-parser setup:正文解析器设置:

npm install body-parser

app.js:应用程序.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:你的文件.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:你的文件.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:应用程序.js:

This is where you handle the actual POST request.这是您处理实际 POST 请求的地方。 When the form button is clicked, your server will receive a HTTP POST request with the route /location , since the form's action="/location" (in my version)单击表单按钮时,您的服务器将收到一个带有路由/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 );
});

On a side note, if you or anyone is looking for a good class to start learning development, try this Udemy course.附带说明一下,如果您或任何人正在寻找一个好的课程来开始学习开发,请尝试Udemy 课程。 It costs around 12 USD but it is worth it if you are just starting out.它的成本约为 12 美元,但如果您刚刚开始,这是值得的。

Note: I don't make anything by you buying that course, nor do I know the instructor.注意:您购买该课程我没有做任何事情,我也不认识讲师。 I am recommending it because it was helpful to me.我推荐它,因为它对我有帮助。

Note: NEVER pay more than 15 USD for a course on Udemy!!!注意:永远不要为 Udemy 上的课程支付超过 15 美元的费用!!! If they are trying to charge you more then 15 USD do the following:如果他们试图向您收取超过 15 美元的费用,请执行以下操作:

  • signout of Udemy退出 Udemy
  • clear your browser cache and cookies清除浏览器缓存和 cookie
  • change your IP address (you can use a VPN, or go to a friends house)更改您的 IP 地址(您可以使用 VPN,或去朋友家)
  • create a new email/Udemy account and all the prices should drop for you创建一个新的电子邮件/ Udemy 帐户,所有价格都会为您下降

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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