jQuery $.ajax 发布到同一个文件中的 PHP 不起作用


jQuery $.ajax post to PHP in the same file not working

这是代码:

<script>
$( document ).ready(function() {
    $( ".button" ).click(function() {
        var clickBtnValue = $(this).val();
        $.ajax({
            //url: '', // url is empty because I'm working in the same file
            data: {'action': clickBtnValue},
            type: 'post',
            success: function(result) {
            alert("action performed successfully"); //this alert is fired
            }
    });
});
});
</script>
<div>Button clicked:
<?php 
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'insert':
            echo "select button!";
            break;
        case 'select':
            echo "insert button!";
            break;
    }
}
?>
</div>
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />

在检查器中,我可以看到一个已发布的值,那么为什么echo "insert button!";echo "select button!";不起作用呢?

你必须在 javascript 中更改div 中的内容,就像你对 alert() 所做的那样。如果您正在处理同一个文件,PHP 应该位于文件的开头。

<?php 
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'insert':
            echo "insert button!";
            break;
        case 'select':
            echo "select button!";
            break;
    }
    exit;
}
?>
<script>
$( document ).ready(function() {
    $( ".button" ).click(function() {
        var clickBtnValue = $(this).val();
        $.ajax({
            //url: '', // url is empty because I'm working in the same file
            data: {'action': clickBtnValue},
            type: 'post',
            success: function(result) {
                alert("action performed successfully"); //this alert is fired
                $('div#result').text('Button clicked: ' + result);
            }
        });
    });
});
</script>
<div id="result"></div>
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />