返回上一个功能

时间:2016-06-04 09:31:56

标签: javascript php jquery mysql ajax

我正在使用ajax来检查是否使用了用户名。如果使用用户名,则返回false给表单提交功能。我正在使用MySQL。

的index.php

    Dim t As Integer = DataGridView1.RowCount - 1

    Dim groundX(t) As Double
    Dim groundY(t) As Double
    Dim groundZ(t) As Double
    Dim photoX(t) As Double
    Dim photoY(t) As Double


    For i As Integer = 0 To t
        groundX(i) = Double.Parse(DataGridView1.Rows(i).Cells("gX").Value)
        groundY(i) = Double.Parse(DataGridView1.Rows(i).Cells("gY").Value)
        groundZ(i) = Double.Parse(DataGridView1.Rows(i).Cells("gZ").Value)
        photoX(i) = Double.Parse(DataGridView1.Rows(i).Cells("pX").Value)
        photoY(i) = Double.Parse(DataGridView1.Rows(i).Cells("pY").Value)
    Next

user_check.php

$("#register-form").submit(function(){
    var un = $("#un").val();
    $.ajax({
        type: "GET",
        url: "user_check.php",
        dataType: "html",
        data: {un: un},
        success: function(data){

        }
    });
});

如果数据为1,我如何将false返回到寄存器表单提交函数,如果为0则返回true?有更简单的方法吗?

2 个答案:

答案 0 :(得分:3)

使用JSON。在PHP中:

echo json_encode($count > 0);

在Javascript中,指定type: 'json'而不是type: 'html'。然后data将为truefalse

但是,由于AJAX是异步的,因此无法从此返回值。

您需要做的是阻止.submit()功能中的正常表单提交。然后在success:函数中,检查响应并提交表单(如果成功)。

$("#register-form").submit(function(e){
    e.preventDefault();
    var un = $("#un").val();
    $.ajax({
        type: "GET",
        url: "user_check.php",
        dataType: "json",
        data: {un: un},
        success: function(data){
            if (data) {
                $("#register-form")[0].submit(); // really submit the form
            } else {
                alert("Username is taken");
            }
        }
    });
});

答案 1 :(得分:0)

请尝试此

<script>
    $("#register-form").submit(function(){
    var un = $("#un").val();
    $.ajax({
        type: "POST",
        url: "user_check.php",
        data: {un: un},
        success: function(data){
           alert(data);
        }
    });
});
</script>

<?php 

$db = mysqli_connect("localhost","root","","webcap");
$user = $_POST['un'];
$query = mysqli_query($db,"SELECT * FROM users WHERE username='".$user."'");
$count = mysqli_num_rows($query);
echo $count;
if($count>0){echo TRUE;}
else{echo FALSE;}
?>