javascript - 调用 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 年前,所以这有点困难 :)
谢谢!
解决方案
如果您先点击发送电子邮件的 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>
推荐阅读
- excel - 用它的可见值替换单元格值
- android - 无法在反应原生“/bin/sh:adb:command not found”中访问我的 android 模拟器
- mongodb - 在 MongodB 中编写聚合查询
- postgresql - 未使用 DBeaver 在 Postgresql 中创建表/函数
- json - 如何用字典键值填充表格视图?
- flutter - 在颤动中将滑块值更改为列表项值
- awk - 为什么 gawk 在“printf”调用之间添加额外的空格?
- azure - 在不同的 Azure 资源组中共享应用服务计划
- mysql - LAMP/MySQL - SQL 批量插入期间的运行时间延迟
- azure - Azure (Durable) Functions - 管理并行性