java-script 函数被调用两次

java-script function is called twice

本文关键字:两次 函数 调用 java-script      更新时间:2023-09-26

我正在制作一项服务,该服务在点击时将用户的Facebook信息保存到数据库中。现在的问题是我的服务被调用了两次。我不知道为什么它以这种方式行事。请帮忙。

索引.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/jquery.jgrowl.min.css">
        <script type="text/javascript" src="scripts/jquery.js"></script>
        <script type="text/javascript" src="scripts/jquery.validate.min.js"></script>
        <script type="text/javascript" src="scripts/jquery.blockUI.js"></script>
        <script type="text/javascript" src="scripts/jquery.jgrowl.min.js"></script>
        <script type="text/javascript" src="scripts/fb.js"></script>
</head>
<body>
<div id="fb-root"></div>
<table align="center">
    <tr>
        <th>Registration Method</th>
    </tr>
    <tr>
        <th><input type="button" value="Login With Facebook" id="fb-auth">   </th>
    </tr>
</table>
</body>
</html>

FB.js

        window.fbAsyncInit = function() {
                FB.init({
                  appId      : 'xxxxxxxxxxxxxxxx',
                  xfbml      : true,
                  version    : 'v2.1',
                  status     : true, 
                  cookie     : true,
                  oauth      : true
                });


                function updateButton(response) {
                    var button = document.getElementById('fb-auth');
                    if (response.authResponse) { // in case if we are logged in
                        var userInfo = document.getElementById('user-info');
                        FB.api('/me', function(response) {
                           var socialMediaRegistration={};
                           socialMediaRegistration['name']=response.name;
                           socialMediaRegistration['profileId']=response.id;
                           socialMediaRegistration['email']=response.email;
                           socialMediaRegistration['socialPlatform']="Facebook";
                           var mydata={};
                           mydata['socialMediaRegistration']=socialMediaRegistration;
                           submitData(mydata);
                        });
                        button.onclick = function() {
                            FB.logout(function(response) {
                                window.location.reload();
                            });
                        };
                    } else { // otherwise - dispay login button
                        button.onclick = function() {
                            FB.login(function(response) {
                                if (response.authResponse) {
                                    window.location.reload();
                                }
                            }, {scope:'email,public_profile'});
                        }
                    }
                }
                // run once with current status and whenever the status changes
                FB.getLoginStatus(updateButton);
                FB.Event.subscribe('auth.statusChange', updateButton);    
            };
              (function(d, s, id){
                 var js, fjs = d.getElementsByTagName(s)[0];
                 if (d.getElementById(id)) {return;}
                 js = d.createElement(s); js.id = id;
                 js.src = "http://connect.facebook.net/en_US/sdk.js";
                 fjs.parentNode.insertBefore(js, fjs);
               }(document, 'script', 'facebook-jssdk'));
            (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol + 'http://connect.facebook.net/en_US/all.js';
                if (document.getElementById('fb-root')) 
                    {document.getElementById('fb-root').appendChild(e);};
            }());
function submitData(data){
alert("this is below the submitdata");
alert(JSON.stringify(data));
        $.support.cors = true;
        $.jGrowl.defaults.position = 'center';
        $.ajax({
             type: "POST",
             url: "http://localhost:8080/components/services/saveSocialMedia",//use ur service
             data: JSON.stringify(data),
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {
                 $.unblockUI();
                 $.blockUI({ message: null });
                 $.jGrowl('Application Reference: '+data["Id"]+' is created. <br/><br/>Have a nice day!', {
                    sticky: true,
                    header: 'Request Submitted Successfully!',
                    life: 5000,
                    speed:  'slow',
                    animateOpen: { 
                        height: "show",
                        width: "show"
                    },
                    animateClose: { 
                        height: "hide",
                        width: "show"
                    },
                    close: function(e,m,o) {
                        $.unblockUI();
                        //$("#ApplicationRequestForm")[0].reset();
                    },
                    click: function(msg) {
                        $.unblockUI();
                        //$("#ApplicationRequestForm")[0].reset();
                        $("div.jGrowl").jGrowl("close");
                        return true;
                    }
                }); 
             },
             error: function (jqXHR, status) {
                 $.unblockUI();
                 $.blockUI({ message: null });
                 $.jGrowl('Please try again after sometime.', {
                    sticky: true,
                    header: 'Ouch! An Unexptected Error Occurred.',
                    life: 5000,
                    speed:  'slow',
                    animateOpen: { 
                        height: "show",
                        width: "show"
                    },
                    animateClose: { 
                        height: "hide",
                        width: "show"
                    },
                    close: function(e,m,o) {
                        $.unblockUI();
                    },
                    click: function(msg) {
                        $.unblockUI();
                        $("div.jGrowl").jGrowl("close");
                        return true;
                    }
                }); 
                console.log(jqXHR);
             }
          });
    }

当您使用 CORS 时,您的某些请求会预先发布。根据文档:

与简单请求(如上所述)不同,"预检"请求首先通过 OPTIONS 方法向其他域上的资源发送 HTTP 请求,以确定实际请求是否可以安全发送。 跨站点请求是像这样预检的,因为它们可能会对用户数据产生影响。 特别是,在以下情况下,将预检请求:

  • 它使用 GET、HEAD 或 POST 以外的方法。 此外,如果使用 POST 发送内容类型而不是 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 的请求数据,例如,如果 POST 请求使用 application/xml 或 text/xml 向服务器发送 XML 有效负载,则请求是预检的。
  • 它在请求中设置自定义标头(例如,请求使用诸如 X-PINGOTHER 之类的标头)

您使用的是 POST 方法,但您的内容类型设置为 application/json; charset=utf-8 ,因此浏览器将首先使用 OPTIONS 方法发送请求,然后发送您的POST

并且,为了使浏览器允许POSTOPTIONS响应必须包含某些标头:

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

这些告诉浏览器http://foo.example是允许的源,POSTGETOPTIONS 是允许的方法,并且 X-PINGOTHER 是允许的标头。

因此,您的服务被调用两次,因为它是由浏览器自动预检的。