简体   繁体   English

如何使ap:commandButton提交表单(未调用JavaScript提交操作)

[英]How to make a p:commandButton submit a form (JavaScript submit action not called)

I am developping several GUIs using primefaces and I would like to warn the user before leaving the website. 我正在使用primefaces开发多个GUI,我想在离开网站之前警告用户。 I found a perfectly working solution here: How to detect unsaved data in form when user leaves the page? 我在这里找到了一个完美的解决方案: 当用户离开页面时如何检测表单中未保存的数据? Here's the JavaScript code I am using (found in the link) 这是我正在使用的JavaScript代码(在链接中找到)

$(function() {
    // Set the unload message whenever any input element get changed.
    $(':input').on('change', function() {
        setConfirmUnload(true);
    });

    // Turn off the unload message whenever a form get submitted properly.
    $('form').on('submit', function() {
        alert('I am here');
        setConfirmUnload(false);
    });
});

function setConfirmUnload(on) {
    var message = "You have unsaved data. Are you sure to leave the page?";
    window.onbeforeunload = (on) ? function() {
        return message;
    } : null;
}

My problem is that my primefaces save button is ajax and doesn't call the 'submit' action. 我的问题是我的primefaces保存按钮是ajax,并且不调用“ submit”操作。 And the user will be alerted that he is leaving the website also after saving the page. 并且在保存页面后,还将提醒用户他也将离开网站。 The code of the commandButton is the following: commandButton的代码如下:

<p:commandButton value="save" id="saveButton" validateClient="true" actionListener="#{myView.save}" update="description name" style="float:right">     </p:commandButton>

I tried to add an "execute form" in a ajax call: 我试图在ajax调用中添加“执行表单”:

<p:commandButton value="save" id="saveButton" validateClient="true" actionListener="#{myView.save}" update="description name" style="float:right">
<p:ajax execute="@form"> 
</p:commandButton>

but it also did not work. 但它也没有用。 If the button is set as $ajax="false"$ everything works fine, but I would like to avoid it. 如果按钮设置为$ ajax =“ false” $,则一切正常,但我想避免这种情况。 Can anyone help? 有人可以帮忙吗? Thanks a lot! 非常感谢!

add this function in your script. 在脚本中添加此function

function save(){
    alert('I am here');
    setConfirmUnload(true);
}

and insert onclick="save();" 并插入onclick="save();" in your commandButton 在您的commandButton中

Isn't it possible to give your button the additional attribute type="submit"? 是否可以为按钮提供附加属性type =“ submit”? Don't know if that works in primefaces, works in other frameworks though :) 不知道这是否适用于primefaces,但适用于其他框架:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM