调用 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

并且不需要这个函数来返回。我还需要阿贾克斯吗?这段代码是否正确,还是我缺少一些语法?我上一次使用JavaScript和Axax是在10年前,所以这有点挣扎:)

谢谢!

如果您先点击发送电子邮件的 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>

最新更新