我的 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>
或者,当文档准备好用于 JS 时,将其包装在回调中。

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