Ajax如何与PHP一起使用?

我在使用ajax和php时遇到了点麻烦。我想做的是调用ajax函数,该函数从表单的输入中获取值,并检查数据库中是否存在该电子邮件。这是我当前的javascript:

//Checks for Existing Email
function checkExisting_email() {
    $.ajax({
        type: 'POST',
        url: 'checkExist.php',
        data: input
    });

emailExists = checkExisting_email();

//If it exists
if (emailExists) {
    alert("This email already exists!");
}

但问题是我压根无法收到提醒。在我的PHP函数中,它检查输入的是用户名还是电子邮件,然后在任一列中查找它。如果找到它,则返回true,否则返回false。/p>

include ('func_lib.php');
connect();
check($_POST['input']);

function check($args)
{
    $checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
    if (!preg_match($checkemail, $args)) {
        //logic for username argument
        $sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        //logic for email argument
        $sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    }

}

所以我的问题是,ajax如何响应这些返回值,以及如何相应地使ajax函数起作用? 主要是为什么这不起作用?

非常感谢您的帮助,谢谢!

You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.

Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.

Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:

echo (check($_POST) ? 'true' : 'false');

You can now check the content in JavaScript.

Basically ajax is a hand-shaking routine with your server.

Ajax:

$.post('yoursite.com/pagewithfunction.php',
    {postkey1:postvalue1, postkey2:postvalue2...},
    function (response) {
       // response is the data echo'd by your server
    }, 'json'
);

pagewithfunction:

yourFunction(){
   $var1 = $_POST['postkey1'];....
   $result = dosomething($var1..);
   echo json_encode($result); // this is passed into your function(response) of ajax call
}

So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.