在提交表单时运行AJAX代码

wil*_*amg 0 html php email ajax jquery

这是我的表格:

<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" />
</form>
Run Code Online (Sandbox Code Playgroud)

而我的jQuery:

    $(document).ready(function() {

        $('form').submit(function() {
            email = $('input[name=email]').val();
            $.post("/scripts/addemail.php", {email_address:email}, function(data){

               if(data == "invalid") { 
                alert("invalid"); 

               } else if(data == "used") { 
                alert("used"); 

               } else if(data == "success") { 
               alert("success"); 

               } else {
                alert("error"); 

               }
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

和我的PHP:

<?php

mysql_connect ('localhost', '********', '********') ;
mysql_select_db ('Blog');

function check_email($input) {

     $input = htmlspecialchars(strip_tags($input));

     $checkaddress = "SELECT * FROM emails WHERE email='$input'"; 
     $query = mysql_query($checkaddress);

     if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $input)) {
          return "invalid";
     } else if ( mysql_num_rows($query) >= 1 ) { 
        return "used"; 
     } else {
        $result = mysql_query("INSERT INTO emails (email) VALUES ('$input')");
        return "success";
    }
}

$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>
Run Code Online (Sandbox Code Playgroud)

问题是它转到action ="/ scripts/addemail_fb.php"而不是jQuery.我是AJAX的新手,也是jQuery的AJAX,但我已经使用jQuery很长一段时间了.

我认为有两个问题:我不认为信息正确地发送到jQuery,我不知道如何处理PHP中的密钥:值对(email_address:email).谢谢你的帮助!是的,我显然是初学者.

cza*_*aic 5

return false;在表单的提交函数中添加一个以防止默认行为.