簡體   English   中英

我的onclick事件是在頁面加載時執行的,而不是在單擊按鈕時執行的,我不知道為什么

[英]My onclick event performs when the page loads instead of when the button is clicked, and i don't know why

    function ajax_post() {

    var xmlhttp=new XMLHttpRequest();
    var working='working';
    xmlhttp.open("POST","process_form.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            // success
            var return_data = xmlhttp.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }

xmlhttp.send(working);
alert("The ajax function is running!");
document.getElementById("status").innerHTML = "Processing. Please wait...";

}

var costButton = document.getElementById('cost-value');

costButton.onclick = ajax_post();

我正在嘗試學習如何從javascript中獲取變量並將其發送到單獨的php文件中進行處理(我將其放入數據庫中)。 我的第一個問題似乎是當我單擊成本值按鈕時函數運行,而不是在頁面加載時運行,而第二個問題似乎是我嘗試發送(工作)的變量實際上並沒有得到發送。 這對我來說是很新的。 有什么辦法嗎?

您正在將onclick設置為函數的返回值,因為您正在執行帶有括號的函數。 onclick刪除() ,它將按預期工作。

costButton.onclick = ajax_post; 

為了使其正常工作,您需要確保:

該腳本出現在結束body標記</body>
或將其包裝在回調中,以供文檔何時可用於JS。

 document.addEventListener("DOMContentLoaded", function() {
   // Your code here
 })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM