Javascript API调用后撤消preventDefault()

Javascript API调用后撤消preventDefault(),javascript,Javascript,我正在编写外部脚本来检查电子商务商店的可用性。当按下“添加到购物篮”按钮时,我正在调用API并检查产品是否可供订购。但是,我不知道如何撤消preventDefault()。当条件为true时,按钮下的事件应继续,并且产品应添加到篮子中,就像没有脚本一样 button.addEventListener('click', (event) => { event.preventDefault(); fetch(`https://example.com/api.php?part=${partId}`

我正在编写外部脚本来检查电子商务商店的可用性。当按下“添加到购物篮”按钮时,我正在调用API并检查产品是否可供订购。但是,我不知道如何撤消preventDefault()。当条件为true时,按钮下的事件应继续,并且产品应添加到篮子中,就像没有脚本一样

button.addEventListener('click', (event) => {
event.preventDefault();
fetch(`https://example.com/api.php?part=${partId}`)
    .then(function (response) {
        return response.json();
    })
    .then(function (jsonRes) {
        console.log(JSON.stringify(jsonRes));
        if (jsonRes.part.partFound == true) {
            console.log('Found! Processing...');
            // REMOVE preventDefault() and process
        } else {
            console.log('Not found! Aborting...', partId);
        }
    });

}))

您可以尝试下面的代码:

async function apiCall(onSuccess, onError) {
    fetch(`https://example.com/api.php?part=${partId}`)
        .then(function (response) {
            return response.json();
        })
        .then(function (jsonRes) {
            console.log(JSON.stringify(jsonRes));
            if (jsonRes.part.partFound == true) {
                console.log('Found! Processing...');
                onSuccess(jsonRes);
            } else {
                console.log('Not found! Aborting...', partId);
                onError();
            }
        });
}

button.addEventListener('click', (event) => {
    // show loading or something
    apiCall(function (response) {
        // success
    }, function () {
        // error
    });
});

如果您的按钮是
type=“submit”,请将其更改为
type=“button”`。这个

a) 我不会提交表格

b) 这意味着您不必使用
preventDefault
来阻止表单提交

这仅仅意味着您需要决定如何提交数据,您可以通过对API端点的另一个AJAX调用来完成,也可以通过将整个表单提交到服务器来完成,以您的设置为准

//抓取表单和按钮,然后添加事件
//点击按钮
const form=document.querySelector('form');
const button=document.querySelector('button');
addEventListener('click',handleClick,false);
//假API调用
函数fakeAPI(){
返回新承诺((解决、拒绝)=>{
设置超时(()=>{
解析(`API调用!`)
}, 2000);
});
}
函数handleClick(){
console.log('Clicked');
fakeAPI(2000)。然后(数据=>{
//如果找到零件,请提交表单数据
//或者调用另一个fetch来发布数据,
//或者“form.submit()”来发布整个表单
});
}

点击

if(true){…}您不能调用最初绑定到按钮的函数吗?或者,如果是表单提交者,则使用JS提交表单。无法撤消表单提交。您可以调用某个事件,但不能以任何方式暂停该事件并重新启动它。您甚至需要默认设置吗?也许只需将其从提交按钮(如果是一个)更改为type=“button”。是-否则,电子商务商店脚本将向购物篮添加产品+重定向到购物篮子页面。我需要以某种方式停止它,直到我从API接收到数据。如果没有阻止,将触发默认按钮事件。是的,您必须将按钮操作移动到
onSuccess
回调