首页 > 解决方案 > 调用 URL 时对我的 JavaScript 代码感到困惑,不确定是否需要 Ajax 调用

问题描述

我有一个 .html 文件。

在文件中,有一个这样的链接:

<a href="https://www.someOtherWebsite.com/" onclick="clicked('https://www.MyWebsite.com/send_emai.php?subject=hello&body=test')">Some text</a>

据称单击的是调用一个 JavaScript 函数,该函数现在位于同一文件的标题中,看起来像这样(我从网上不同的地方得到了它的一部分):

 <script type="text/javascript">
 function clicked(url) {
   // your server call
   fetch('https://jsonplaceholder.typicode.com/todos/1')
     .then(response => response.json())
     .then(json => console.log(json))
   // open the link in new tab
   window.open(url);
 }
 </script>

我真的只需要导航到 href 中的 URL,但是点击这个 URL,它会向我发送一封关于它的电子邮件:

https://www.MyWebsite.com/send_emai.php?subject=hello&body=test

并且不需要这个函数返回。我还需要 Ajax 吗?这段代码是正确的还是我错过了一些语法?我上次使用 JavaScript 和 Axax 是在 10 年前,所以这有点困难 :)

谢谢!

标签: javascripthtmlajax

解决方案


如果您先点击发送电子邮件的 url,然后离开怎么办?

我不确切地知道 fetch 是如何工作的,但你可以尝试这样的事情:

<a onclick="clicked('https://www.someOtherWebsite.com/')">Some text</a>
<script>
 function clicked(url) {
   // your server call
   fetch('https://www.MyWebsite.com/send_emai.php?subject=hello&body=test')
   .then(() => {window.location.href = url});
 }
</script>

推荐阅读