如何使用外部js文件访问表单?如何从客户端隐藏js的敏感内容?

how to acess form with external js files? how to hide sensitive content of js from client?

我正在使用 emailjs 通过我的免费子域发送电子邮件 website.There 它有两个问题 1).我的 emailjs 帐户 ID、服务 ID 和模板 ID 正在获取 public,因此任何人都可以访问它并通过它发送电子邮件。 2).为了解决它,我使用了以下代码,但它出现在浏览器中 "inspect Element"(开发人员工具)。

     <?php echo "
<script>
   (function(){
      emailjs.init(my user id);
   })();
</script>" ; ?>
    <?php
      echo "<script src='js/formfilled.js'></script>"; 
    ?>

现在我的表单提交按钮是这样的

    <button onclick="email();">
         Send
    </button>

现在我的填表文件是这样的

var myform = $("form#myform");
function email(){

  var service_id = "default_service";
  var template_id = "xxxxxxxxx";

  myform.find("button").text("Sending...");
  emailjs.sendForm(service_id,template_id,"myform")
    .then(function(){ 
        alert("Sent!");
       myform.find("button").text("Send");
    }, function(err) {
       alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
       myform.find("button").text("Send");
    });
}

问题是,当我单击按钮而不是发送电子邮件时,它会重新加载页面。 对不起,如果它太傻了,我完全是初学者,在此先感谢。

更新 如果我将代码放在同一个文件中(不使用外部 js),它就可以工作 代码:--

    <head>
              <script type="text/javascript">
   (function(){
      emailjs.init("xxxxxxxxxxxxxxxxxxxxx");
   })(); </head>
</script>
<body>
            <!-- form is here-->
<script>

var myform = $("form#myform");
myform.submit(function(event){
    event.preventDefault();

  // Change to your service ID, or keep using the default service
  var service_id = "default_service";
  var template_id = "xxxxxxxxxxxxxxxxxxx";

  myform.find("button").text("Sending...");
  emailjs.sendForm(service_id,template_id,"myform")
    .then(function(){ 
        alert("Sent!");
       myform.find("button").text("Send");
    }, function(err) {
       alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
       myform.find("button").text("Send");
    });
  return false;
});
</script>
</body>

但如果我将这段代码放在 formfilled.js 中,它就不起作用了。 背后的原因是什么?

回答: 使用

 event.preventDefault(); 

并在加载按钮之前加载文件。