weixin_33712987 2011-05-08 20:41 采纳率: 0%
浏览 36

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函数起作用? 主要是为什么这不起作用?

非常感谢您的帮助,谢谢!
  • 写回答

2条回答 默认 最新

  • weixin_33738578 2011-05-08 20:45
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥200 关于#c++#的问题,请各位专家解答!
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀