php表单不会用javascript提交

问题描述:

I have a dashboard page, and for the easiest solution I've made the entire page a form (as there are several drop downs scattered across the whole page). I want to implement a feature that can submit the form every 30 minutes, be it with JavaScript, jQuery or anything else, but when I've tried it just refuses to execute the code, so I tried going back to something basi such as submitting the form when the drop-down is changed via "OnChange".

Here is an example snippet of a seperate page with some code from my dashboard page. This in itself should be working but I just can't see why it won't execute the code, maybe I'm missing something obvious? Can you help me fix this:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function submit_my_form(myfield)
{
   myfield.form.submit();
}
function submitForm() {
    document.getElementById("branchForm").submit();
}
</script>
</head>
<body>
<?php   
$branch_array = array(
        array(1,"BRANCH 1",1, "http://BRANCH.BRANCH1:1"),
        array(2,"BRANCH 2",1, ""),
        array(3,"BRANCH 3",3, "http://branch3:3"),
        );
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST" name="branchForm" id="branchForm">
    <select name="query" id="query" class="select" onChange="submit_my_form(this);">
    <?php
    foreach ($branch_array as $x) { // populate select box with branches available from array

        echo '<option value ="'.$x[0].'"';
        if (isset($_POST['query']) && $_POST['query'] == $x[0]) 
        {
            echo ' selected="selected" >'.$x[0].". ".$x[1].'</option>'; 
        } else { 
            echo ' option="'.$x[0].". ".$x[1].'">'.$x[0].". ".$x[1].'</option>'; 
            }
    }
    ?>
    </select>
        <input type="submit" name="submit" value="Refresh" class="btnRefresh" />
        <input type="button" value="go" name="click" onClick="submitForm();" />
    </form>
    <?php echo "<br/>Output: {$_POST['query']}"; ?>
</body>
</html>

Nothing happens when the drop-down is changed, and nothing happens when the "go" button is pressed.

Since you don't mind using jQuery, here you go:

var form = $("#formId");
$("select[name=selectField]").on("change", function(e){
    form.trigger("submit");
});

http://jsfiddle.net/zt8zz1j5/

All it essentially does is listen for change on the select element, and simply triggers the submit event on the form. Of course you'll need to change the names and IDs to fit your code, but I'm sure you can handle that :), and remember to include jQuery in the document.

And for the button it's the same thing. You listen for the 'click' event and then trigger 'submit' on the form.