gpt4 book ai didi

jquery:表单内的 ajax POST - 防止 ajax 调用时提交表单

转载 作者:行者123 更新时间:2023-12-03 22:21:02 25 4
gpt4 key购买 nike

我正在尝试在表单(Drupal 节点编辑表单)内执行 ajax 调用,但似乎在执行调用时,它出于某种原因提交了表单。这是示例代码:

jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: {"text": jQuery("#edit-body").html()
},
success: function(result){
console.log(result);
}
});

我可以通过在控制台中执行它来复制它,但我将其附加到表单内的按钮单击功能。关于在 POST ajax 调用中阻止表单提交的任何提示?

这是请求的完整代码

        jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button"  id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>'); 
jQuery("#proofread_bot-submit").click(function(event){
event.preventDefault();
jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");

jQuery.ajax({
type: "POST",
url: "proofread_bot/check",
dataType: "html",
data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
},
success: function(proofread_result){
jQuery("#proofread_bot-submit").after(proofread_result);
jQuery("#proofread_bot_throbber").remove();
}
});
});

最佳答案

您需要重写表单的 onsubmit 事件以防止提交:

$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (isValid) {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
e.preventDefault();
return false;
});

通过调用

e.preventDefault();
return false;

您阻止发生同步回发。

更新:如果您不想覆盖表单提交,也许您可​​以将按钮放在表单标记之外(如果需要,您可以使用 css 调整位置)?

关于jquery:表单内的 ajax POST - 防止 ajax 调用时提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com