Javascript 表单提交调用JS函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2396697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:06:29  来源:igfitidea点击:

Calling JS Function on Form Submit

javascriptfacebookformsonsubmit

提问by Russell C.

I have created a JS function which executes fine when it's included an the 'onclick' action of standard HTML link tag as follows:

我创建了一个 JS 函数,当它包含标准 HTML 链接标签的“onclick”操作时,它可以正常执行,如下所示:

<a href="#" onclick="return fb_CheckPermission('publish_stream');">test</a>

However where I really want to use this function is on the 'onsubmit' action of a form but when I include it as follows the function no longer seems to be executing:

但是,我真正想使用此函数的地方是表单的“onsubmit”操作,但是当我按如下方式包含它时,该函数似乎不再执行:

<form action="page.pl" id="disable-submit" name="status-form" method="POST" onsubmit="return fb_CheckPermission('publish_stream');">

What the 'fb_CheckPermission()' JS function basically does is use Facebook Connect to check to make sure the user has granted us a specific permission and if not it tells Facebook Connect to prompt the user to grant the permission. Here is the code for the JS function:

'fb_CheckPermission()' JS 函数的主要作用是使用 Facebook Connect 来检查以确保用户已授予我们特定的权限,如果没有,它会告诉 Facebook Connect 提示用户授予权限。下面是JS函数的代码:

1. function fb_checkPermission(permission) {
2.  FB.ensureInit(function() {
3.      FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) {
4.          if(!hasPermissions){
5.              FB.Connect.showPermissionDialog(permission,function (status){
6.                  if(!status) {
7.                      if(permission == 'offline_access') {
8.                          // save session
9.                      }                       
10.                 }
11.             });
12.         }
13.     });
14. });
15.}

What this code does is as follows:

这段代码的作用如下:

Line 2: Make sure Facebook Connect JS library is loaded
Line 3: Checks to see if the current Facebook Connect user has granted a specific permission
Line 5: If the permission hasn't been granted then prompt the user with the permission dialog
Line 7: In the case of the 'offline_access' permission save the session key once granted

The user experience I'm trying to achieve is that when a user submits the form I'll check to see if they have granted a specific permission and if not prompt them for the permission before submitting the form. If the user has already granted the permission the form should just submit. For those users who are prompted the form should submit after they either choose to grant the permission or if the deny the request which I believe the fb_checkPermission() JS function is handling correctly right now. What I'm not sure is if there is some kind of JavaScript issue with how this works on form submission.

我试图实现的用户体验是,当用户提交表单时,我会检查他们是否已授予特定权限,如果未在提交表单之前提示他们提供权限。如果用户已经授予权限,则表单应该提交。对于那些被提示表单的用户,他们应该在选择授予权限或拒绝我认为 fb_checkPermission() JS 函数现在正确处理的请求后提交。我不确定的是,它在表单提交上的工作方式是否存在某种 JavaScript 问题。

As I mentioned, this JS function works perfectly as an onclick action but fails as an onsubmit action so I'm pretty sure that this has something to do with how JavaScript treats onsubmit actions.

正如我提到的,这个 JS 函数可以完美地作为 onclick 操作,但作为 onsubmit 操作失败,所以我很确定这与 JavaScript 处理 onsubmit 操作的方式有关。

I'm stuck so I really appreciate your help in figuring out how to change the JS function to produce my desired user experience. Thanks in advance for your help!

我被卡住了,所以我非常感谢您在弄清楚如何更改 JS 函数以产生我想要的用户体验方面的帮助。在此先感谢您的帮助!

回答by Marko Dumic

The reason your "click on anchor" works is because it does not change your page (location) while all of the Facebook asynchronous calls finish.

您的“点击锚点”起作用的原因是它不会在所有 Facebook 异步调用完成时更改您的页面(位置)。

When you attach the same function to the submit handler the function returns before Facebook stuff gets actually executed, and it does without returning "false" causing the form to proceed with submission earlier than you want it to.

当您将相同的函数附加到提交处理程序时,该函数会在 Facebook 内容实际执行之前返回,并且不会返回“false”,从而导致表单比您希望的更早地继续提交。

What you need to do is return "false" at the end of your onSubmit function to prevent submission and give time to Facebook stuff to finish and then manually submit form at places you want it to be submitted by calling:

您需要做的是在 onSubmit 函数的末尾返回“false”以防止提交并给 Facebook 的内容留出时间来完成,然后通过调用在您希望提交表单的地方手动提交表单:

document.getElementById('disable-submit').submit();

(The handler will not be called if submittion is triggered from the script.)

(如果从脚本触发提交,则不会调用处理程序。)

Unfortunately I don't have Facebook SDK at hand so I can't write the code that I'm sure works 100%, but it's something along these lines:

不幸的是,我手头没有 Facebook SDK,所以我无法编写我确信 100% 有效的代码,但它是这样的:

function onSubmit () {
    doStuffAsynchronously(function () {
        if (everythingIsOK) {
            // proceed with submission
            document.getElementById('formId').submit();
        }
    });

    return false;
}

回答by pattersonc

Try putting the javascript call on the input you are using to initiate the submit.

尝试将 javascript 调用放在您用来启动提交的输入上。

回答by Darkyo

I think basically that your browser tends to use default validation form (page.pl / method POST) instead of doing what you think it does Try this

我认为基本上你的浏览器倾向于使用默认的验证表单(page.pl / method POST)而不是做你认为它做的事情试试这个

<form action="page.pl" id="disable-submit" name="status-form"
      method="POST" onsubmit="returnFbChPermissionAndPreventDefaultAction();">
    <script type="text/javascript">
        var returnFbChPermissionAndPreventDefaultAction = function(){ 
           //prevent default
           if (event.preventDefault) { 
               event.preventDefault(); 
           } 

           //specific for IE
           valueOfreturn = fb_CheckPermission('publish_stream');
           event.returnValue = valueOfreturn;
           return event.returnValue ; 
        }
    </script>