Visualforce JavaScript Remoting异常:按钮点击后页面自动刷新
解决Visualforce按钮点击触发JS Remoting时页面自动刷新的问题
兄弟,我太懂这个坑了!你遇到的问题核心就是按钮的默认表单提交行为在搞鬼——不管是普通HTML按钮还是Visualforce的commandButton,默认都会触发表单提交,直接刷新页面,不仅会冲掉你刚创建的HTML元素,还会让你的JS逻辑被打断,看起来控制台输出是刷新后才执行,其实是JS Remoting的异步回调在页面刷新后才返回,刚好赶上刷新后的控制台上下文。
下面分两种场景给你解决方案:
场景1:用普通HTML按钮
直接给按钮加上type="button"(默认是submit,会触发表单提交),或者在点击事件里阻止默认行为:
<apex:page controller="YourElementController"> <script> function createNewElement() { // 先阻止按钮的默认提交行为,这步是关键! event.preventDefault(); // 调用JS Remoting Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.YourElementController.getContentForElement}', function(result, event) { if (event.status) { // 创建并插入HTML元素 const newElement = document.createElement('div'); newElement.className = 'custom-element'; newElement.textContent = result; document.getElementById('element-container').appendChild(newElement); console.log('元素创建成功:', result); } else { console.error('Remoting调用失败:', event.message); } }, {escape: true} ); } </script> <div id="element-container"></div> <!-- 方式1:指定type="button",彻底避免默认提交 --> <button type="button" onclick="createNewElement();">创建元素</button> <!-- 方式2:在onclick里返回false,阻止默认行为 --> <button onclick="createNewElement(); return false;">创建元素(备用方式)</button> </apex:page>
场景2:用Visualforce的<apex:commandButton>
这个组件天生就是用来提交表单的,所以必须手动阻止它的默认行为:
<apex:page controller="YourElementController"> <apex:form> <script> // 同上的createNewElement函数... </script> <div id="element-container"></div> <!-- 核心:onclick最后加return false,阻止表单提交 --> <apex:commandButton value="创建元素" onclick="createNewElement(); return false;" /> <!-- 或者设置action为javascript:void(0),禁用默认提交逻辑 --> <apex:commandButton value="创建元素" action="javascript:void(0)" onclick="createNewElement();" /> </apex:form> </apex:page>
额外调试小技巧
- 在
createNewElement函数开头加一句console.log('函数开始执行啦!'),如果页面刷新前控制台能看到这条日志,就坐实了是默认提交在捣乱; - 确保你的JS Remoting回调里的DOM操作是针对当前页面的元素——页面刷新后所有DOM都会重置,所以必须先阻止刷新,才能看到创建的元素。
内容的提问来源于stack exchange,提问作者RealGigex
相关产品推荐
相关产品推荐

