使用 Ajax 为 HTML 按钮 Onclick 调用 PHP 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/754571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Ajax to call PHP function for HTML button Onclick
提问by user84786
I have a an HTML button where I want the onclick to call a PHP function. I need to use AJAX to do this but I am totally lost. There is more that occurs inside the php function, but I didn't see the need of including it. Below is code thus far:
我有一个 HTML 按钮,我希望 onclick 在其中调用 PHP 函数。我需要使用 AJAX 来做到这一点,但我完全迷失了。php 函数内部还有更多内容,但我认为没有必要包含它。以下是迄今为止的代码:
<HTML>
<BODY>
<FORM>
<input text="text" name=airport1 id=airport1 />
<input text="text" name=airport2 id=airport2 />
<input type="button" value="Enter" onclick=PrintDist()/>
</FORM>
</BODY>
</HTML>
<?php
function PrintDist(){
$icao1 = $_REQUEST["airport1"];
$icao2 = $_REQUEST["airport2"];
}
?>
回答by strager
Using jQuery (untested):
使用 jQuery(未经测试):
function PrintDist() {
var submitButton = $(this).find('*:submit');
$.post(this.action, $(this).serialize(), function() {
alert('Form submitted!');
submitButton.attr('disabled', 'false').attr('value', 'Enter');
});
submitButton.attr('disabled', 'true').attr('value', 'Posting...');
return false;
}
Use a proper form as your HTML (for people without Javascript, and for the script to work nicely):
使用适当的形式作为您的 HTML(对于没有 Javascript 的人,并且脚本可以很好地工作):
<form action="xxx" method="post" onsubmit="return PrintDist()">
<input text="text" name="airport1" id="airport1" />
<input text="text" name="airport2" id="airport2" />
<input type="submit" value="Enter" />
</form>

