Ajax JQuery成功函数不工作


Ajax JQuery success function not working

我不确定出了什么问题,但由于某种原因,Ajax中的success函数没有调用该函数。我要求它在PHP完成后调用。

对于PHP,我有$test = 'Hi'; echo json_encode($test);

这是我主页的代码:

<?php
    session_start();
    if(!isset($_SESSION["b2_in"])){
        header("Location: b2.php");
    }
?>
<script>
$(document).ready(function(){   
    $("form input:submit").click(function() {
        $.ajax({
            type: "POST",
            url: 'b2_send.php',
            data: $('form').serialize(),
            dataType: 'json',
            //beforeSend: function(){ $("#send").val('Sending...');},
            success: function(data) {
                TestFunction();
            },
            statusCode: {
                403: function(e) {
                    $("say").highlight();
                    $("#message").html(e.responseText);
                }
            }
        });
    return false;
    });
});
function TestFunction(){
    $("#message").val("");
}
</script>
<say>
    <form> 
        <input type="text" name="message" class="Message" id="message"/>
        <input type="submit" name="send" value='Say' id="send"/>
        <span id="message" style="font-weight:bold;color:red;"></span>
    </form>
</say>

试试这个

span是DOM的块元素,因此要为其设置数据,需要使用$(id).html(data);而不是val()

此外,你应该为dom中的每个元素都有不同的id,它总是选择它在dom中得到的第一个id,在你的情况下,它是

<input type="text" name="message" class="Message" id="message"/>,因此它将更改此元素的值

<script>
$(document).ready(function(){   
    $("form input:submit").click(function() {
        $.ajax({
            type: "POST",
            url: 'b2_send.php',
            data: $('form').serialize(),
            dataType: 'json',
            //beforeSend: function(){ $("#send").val('Sending...');},
            success: function(data) {
                TestFunction();
            },
            statusCode: {
                403: function(e) {
                    $("say").highlight();
                    $("#message").html(e.responseText);
                }
            }
        });
    return false;
    });
});
function TestFunction(){
    $("#message").html("");
}
</script>