javascript - 终止 javascript 执行
问题描述
我可以找到一种方法来从我的第一次提取中终止我的 javascript 执行:
document.querySelector('#elsubmit').onclick = (event) => {
fetch('/', {
method: 'POST',
body: JSON.stringify({
nombrelink: nombrelink
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"X-CSRFToken": getCookie('csrftoken'),
"Accept": "application/json"
}
})
.then(response => response.json())
.then(result => {
if (result['nadie']) {
}
else {
document.getElementById('spanthelinkbox').style.borderColor = 'red';
document.getElementById('spanthelink').style.display = 'block';
document.getElementById('spanthelink').innerHTML = 'Link ya tomado';
event.preventDefault();
return;
return;
return false
return false
return false
}
});
fetch(`https://www.url.com/${urlname}`, {
method: 'POST',
body: formData,
headers: {
"X-CSRFToken": getCookie('csrftoken')
}
})
.then(response => response.json())
.then(result => {
window.location = "https://www.url.com/" + result['urlname'].toLowerCase()
})
}
代码到达所有写入的地方,return false
但它无法阻止下一次提取运行。我想停止执行最后一次提取,但使用 return false
,event.preventDefault();
和return;
似乎不起作用。就像无法停止父事件一样。
有任何想法吗?
解决方案
Fetch 返回一个 Promise,你可以链接多个 Promise,并在第二个请求中使用第一个请求的结果,以此类推。
var result =('/', {
method: 'POST',
body: JSON.stringify({
nombrelink: nombrelink
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"X-CSRFToken": getCookie('csrftoken'),
"Accept": "application/json"
}
}).then(response => response.json())
.then(result => {
if (result['nadie']) {
return (`https://www.url.com/${urlname}`, {
method: 'POST',
body: formData,
headers: {"X-CSRFToken": getCookie('csrftoken')}
})}
else {
document.getElementById('spanthelinkbox').style.borderColor = 'red';
document.getElementById('spanthelink').style.display = 'block';
document.getElementById('spanthelink').innerHTML = 'Link ya tomado';
event.preventDefault();
return false;
}
});
// I'm using the result variable to show that you can continue to extend the chain from the returned promise
result.then(function(r) {
console.log(r); // 2nd request result
});
推荐阅读
- php - PHP Paypal SDK - 获取 20 条最新交易
- python - 如何从不同文件夹中的文件导入 python 类?
- powershell - 公司用户和 Azure AD 用户到底有什么区别?
- angular - Angular OAuthModule 配置工厂
- python - 如何处理 np.array 作为图像生成器中的训练集
- r - 用ggplot绘制最佳拟合线以在r中进行回归
- javascript - 通过 Chrome 扩展连接到 Postgres 数据库
- typescript - 鼠标滚轮功能在苗条上返回错误
- c++ - 编译 GTKmm 程序时出现“架构 x86_64 的未定义符号”错误
- .net - IHttpClientFactory 和读取 Cookie