Bootstrap5标签页多Contact Form7提交成功后触发Ajax请求失败如何解决
你当前代码的问题在于document.querySelector('.wpcf7')仅会返回页面中第一个匹配到的Contact Form 7表单元素,其余标签页内的表单都没有绑定wpcf7mailsent事件监听器,因此提交后不会触发对应的Ajax逻辑。
解决方案
推荐使用事件委托的方式实现全局监听,不需要逐个绑定表单,哪怕是后续动态加载的表单也能正常生效,代码如下:
document.addEventListener( 'wpcf7mailsent', function( event ) { // 可通过event.target获取当前提交的表单元素,方便为不同表单配置不同的传输数据 // 比如你给每个表单加了data-custom-id自定义属性,就可以用event.target.dataset.customId取值区分 var dataSet = {set of serialized data}; $.ajax({ type: "POST", url: "url", data: dataSet, dataType:"JSONP", success: function(response) { console.log( response ); }, error: function (data, errorThrown) { console.log(errorThrown); } }); }, false );
如果你更倾向于逐个绑定静态存在的表单,也可以使用如下写法:
// 选中页面所有CF7表单 var wpcf7Elms = document.querySelectorAll( '.wpcf7' ); // 遍历所有表单逐个绑定事件 wpcf7Elms.forEach(function(wpcf7Elm) { wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) { var dataSet = {set of serialized data}; $.ajax({ type: "POST", url: "url", data: dataSet, dataType:"JSONP", success: function(response) { console.log( response ); }, error: function (data, errorThrown) { console.log(errorThrown); } }); }, false ); });
如果不同标签页的表单需要传输不同的数据,可以通过event.target获取当前提交的表单DOM对象,读取表单上的自定义属性或者表单内的字段值来动态生成dataSet即可。
内容的提问来源于stack exchange,提问作者WP Learner
相关产品推荐
相关产品推荐

