Use Ajax to call PHP function for HTML button Oncl

2020-02-16 03:11发布

问题:

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>
<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"];
    }
?>

回答1:

Using jQuery (untested):

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):

<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>


回答2:

Use any javascript library to make ajax calls to the php script on the server. For example:

  • jquery
  • prototype

Or if you just want really simple stuff, take a look at the sajax ajax toolkit for php