[英]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.