jQuery $ .ajax发布到同一个文件中的PHP无效

时间:2014-12-24 08:54:03

标签: php jquery html ajax

这段代码:

<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!";无效?

1 个答案:

答案 0 :(得分:3)

您必须更改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" />