如何在表单提交中使用jquery ajax

时间:2013-04-02 19:40:28

标签: php jquery ajax

现在将代码更改为此。表单位于subscribe.php中,它包含在索引页面中。

<form class="subscribe" id="email" method="get">
    <input class="email" id="emailaddress" name="email" type="text" placeholder="EXAMPLE@EMAIL.COM" required>
    <input class="button" type="submit" id="emailSub" value="Subscribe">
</form>
<div id="subResult"></div>

Jquery位于索引页的底部

$(document).ready(function() {
    $('#emailSub').click(function() {
        var email = $('#emailaddress').val();
        alert(email);
        $.ajax({
            type: "GET",
            dataType: 'script', //<-Data Type for AJAX Requests(xml | html | script | json)
            url: 'checksub.php',
            data: {
                'e': email
            },
            success: function(result) {
                $("#subResult").html(result);
            }
        });
    })
});

Checksub页面现在正在进行测试。

<?php include 'admin/includes/db_connection.php'; ?>
<?php 
$email = mysqli_real_escape_string($db, $_GET['e']);
echo "test string:";
echo $email;
?>

2 个答案:

答案 0 :(得分:3)

您是否阻止默认点击事件触发提交?

$('#emailSub').click(function(e){
    e.preventDefault();
    var email = $('#emailaddress').val();
    $.ajax({url:"checkemail.php?e="+email,success:function(result){
        $("#subResult").html(result);
    }});
})

答案 1 :(得分:2)

也许你应该改变dataType?试试吧:

$.ajax({
    type: "GET",
    dataType: 'html', //<-Data Type for AJAX Requests(xml | html | script | json)
    url: 'checkemail.php',
    data: {
        'e': email
    },
    success: function(data) {
        $("#subResult").html(result);
    }
});

<input class="button" type="submit" id="emailSub" value="Subscribe">
                              ^ HERE

应该是:

<input class="button" type="button" id="emailSub" value="Subscribe">

因为submit正在提交表单并刷新页面..所以jquery不起作用..

Specifying the Data Type for AJAX Requests