[英]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();
I'm trying to learn how to take a variable from javascript and send it to a separate php file for processing (i'm gonna put this in a database). 我正在尝试学习如何从javascript中获取变量并将其发送到单独的php文件中进行处理(我将其放入数据库中)。 My first problem seems to be that rather than the function running when i click on my cost-value button, it runs when the page loads, and the second problem appears to be that the variable i try to send (working) doesn't actually get sent.
我的第一个问题似乎是当我单击成本值按钮时函数运行,而不是在页面加载时运行,而第二个问题似乎是我尝试发送(工作)的变量实际上并没有得到发送。 This is very new to me.
这对我来说是很新的。 Any solutions?
有什么办法吗?
You're setting the onclick
to the return value of the function, since you're executing the function with the parenthesis. 您正在将
onclick
设置为函数的返回值,因为您正在执行带有括号的函数。 Remove the ()
from the onclick
and it will work as expected. 从
onclick
删除()
,它将按预期工作。
costButton.onclick = ajax_post;
In order for this to work you need to make sure either: 为了使其正常工作,您需要确保:
This script appears just before the closing body tag </body>
该脚本出现在结束body标记
</body>
or you wrap it in a callback for when the document is ready for JS. 或将其包装在回调中,以供文档何时可用于JS。
document.addEventListener("DOMContentLoaded", function() {
// Your code here
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.