繁体   English   中英

为什么settimeout()匿名函数未在javascript中调用该函数?

[英]why settimeout() anonymous function not call the function in javascript?

我在下面编写代码来调用外部Web服务,如果没有debugger,则无法在Safari浏览器中运行。作为解决方案,我添加了settimeout()函数来延迟xhr.send()函数。实际问题如下所述:
我试图在2秒后调用alertFunc,但是settimeout()函数没有调用alertFunc。能帮我解决这个问题吗? 我在下面的代码中定义了我的wordpress footer.php文件。

<script type="text/javascript">
debugger;
var xhr;
      // Create the XHR object.
      function createCORSRequest(method, url) {

           xhr = new XMLHttpRequest();
           if ("withCredentials" in xhr) {
             // XHR for Chrome/Firefox/Opera/Safari.

        xhr.open(method, url, true);


           } else if (typeof XDomainRequest != "undefined") {
             // XDomainRequest for IE.
             xhr = new XDomainRequest();
             xhr.open(method, url);
           } else {
             // CORS not supported.
             xhr = null;
           }
           return xhr;
         }

    function alertFunc(xh) {
        debugger;
           var xh1=xh;
           xh1.send();
       alert("Thank you for contacting us!");

    }
        function saveContactData() {
            var name = document.getElementById('name').value;
            var petname = document.getElementById('petname').value;
            var weight = document.getElementById('weight').value;
             var breed = document.getElementById('breed').value;
            var phone = document.getElementById('phone').value;
            var email = document.getElementById('email').value;
            var findus = document.getElementById('findus').value;
            var location = document.getElementById('location').value;
            var comments = document.getElementById('comments').value;



            var item = {
                "PetInquiryId": -1,
                "ClientName": name,
        "Weight":weight,
                "Breed":breed,
                "PhoneNumber": phone,
                "PetName": petname,
                "Email": email,
                "Comments": comments,
                "Location": location,
                "FindUsName": findus,

            };
        debugger;
             var url = "http://sitename/api/Controllername/functionnme?item=" + JSON.stringify(item);
            var xhr = createCORSRequest("POST",url);   

        //xhr.send();
         setTimeout(alertFunc(xhr), 25000);


       document.getElementById("myForm").reset();


        }


    </script>

包装在封闭中:

setTimeout(function(){alertFunc(xhr);}, 25000);

我通过在以下几行中进行更改解决了问题

xhr.open(method,url,true);

将“ true”替换为“ false”值

xhr.open(method,url,false);

暂无
暂无

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

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