将jQuery AJAX转为原生JS后Symfony表单事件未触发
Symfony动态表单:原生JS替换jQuery后PreSubmit/PostSubmit事件不触发
我基于Symfony实现了一个动态表单,通过下拉菜单选择来显示/隐藏不同字段集,实现逻辑遵循官方的动态表单修改方案。现在我正在移除jQuery,改用原生JavaScript重构下拉框变更时的AJAX请求逻辑(换成XMLHttpRequest或Fetch API),但转换后发现Symfony表单的PreSubmit和PostSubmit事件不再触发,只有PreSetData事件能正常执行。我已经确认Fetch API的请求头和原jQuery AJAX完全一致,但问题仍未解决。
原jQuery AJAX代码
let $ptoType = $("#pto_type"); $ptoType.off('change').on('change', function () { let $form = $(this).closest('form'); let data = {}; data[$ptoType.attr('name')] = $ptoType.val(); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: data, success: function (html) { $('#formStep2').replaceWith( $(html).find('#formStep2') ); } }); });
XMLHttpRequest尝试代码
let ptoType = document.getElementById("pto_type"); ptoType.addEventListener('change', function () { let xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState === XMLHttpRequest.DONE) { if (xmlHttp.status === 200) { document.getElementById("formStep2").innerHTML = xmlHttp.response.getElementById('formStep2').innerHTML; } else if (xmlHttp.status === 400) { alert('There was an error 400'); } else { alert('something else other than 200 was returned'); } } }; xmlHttp.open(form.getAttribute('method'), form.getAttribute('action'), true); xmlHttp.responseType = "document"; xmlHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest") xmlHttp.send(data); });
Fetch API尝试代码
let ptoType = document.getElementById("pto_type"); ptoType.addEventListener('change', function () { let form = document.getElementById('form_pto_entry'); const formData = new FormData(); formData.append('type', ptoType.options[ptoType.selectedIndex].text); fetch(form.getAttribute('action'), { method: form.getAttribute('method'), headers: new Headers({'content-type': 'application/x-www-form-urlencoded; charset=UTF-8','x-requested-with': 'XMLHttpRequest'}), body: formData, }) .then(response => response.text()) .then((body) => { let bodyHtml = ConvertStringToHTML(body); document.getElementById("formStep2").innerHTML = bodyHtml.querySelector('#formStep2').innerHTML; }) .catch((error) => { console.error('Error:', error); }); }); let ConvertStringToHTML = function (str) { let parser = new DOMParser(); let doc = parser.parseFromString(str, 'text/html'); return doc.body; };
通过浏览器开发者工具的网络标签观察,Fetch API的请求头与原AJAX完全匹配,但PreSubmit事件始终不触发。
内容的提问来源于stack exchange,提问作者Robert Wade
相关产品推荐
相关产品推荐

