使用ajax / jquery进行FORM检查

时间:2012-12-26 16:08:11

标签: php javascript jquery ajax

我试图用ajax和jquery发送表单以在同一页面上获得结果。 我有这个代码,我从表单操作链接:

function check()
{

    var html = $.ajax({
        type: "POST",
        url: "reg.php",
        data: $("#reg").serialize(),
        async: false
        }).responseText;
    if(html == "success") { 


        //Indicate a Successful Captcha
        $("#captcha-status").html("<p class=\"green bold\">Success! Thanks you may now proceed.</p>");
    } else {
        $("#captcha-status").html("<p class=\"red bold\">The security code you entered did not match. Please try again.</p>");

    }
}    

然后我有我的php文件:

$query = "SELECT * FROM teemo1 WHERE nick='$nick' and server='$server'";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) )
{
    echo 'success';
}
else
{
$queryy =  

     echo 'fail';
}

 }

我需要在我的页面中显示表单&#34;数据已成功保存&#34;如果失败&#34; Incorrecta data&#34;,但我不知道如何从php文件中获取那些回声到我的ajax脚本。

由于

2 个答案:

答案 0 :(得分:1)

试试这个:

function check(){
    $.ajax({
    type: "POST",
    url: "reg.php",
    data: $("#reg").serialize(),
    async: false,
    success:function(html){
        if(html == "success") { 
            $("#captcha-status").html("<p class=\"green bold\">Success! Thanks you may now proceed.</p>");
        } else {
            $("#captcha-status").html("<p class=\"red bold\">The security code you entered did not match. Please try again.</p>");
            }
        }
    });
}   

答案 1 :(得分:0)

您需要使用success函数并使用成功函数parameter的传递值,在您的情况下为responseText

$.ajax({
    type: "POST",
    url: "reg.php",
    data: $("#reg").serialize(),
    async: false
}).success(function(responseText){        
     if(responseText == "success") {       
      $("#captcha-status").html("<p class=\"green bold\">Success! Thanks you may now proceed.</p>");
     } else {
         $("#captcha-status").html("<p class=\"red bold\">The security code you entered did not match. Please try again.</p>");

     }
});