我在下面编写代码来调用外部 Web 服务,如果没有调试器,它在 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);
关于javascript - 为什么 settimeout() 匿名函数不调用 JavaScript 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013487/