php的ajax加载工作不正常


ajax loading of the php is not working properly

好了,下面是我的代码,当一些人输入用户名和密码并点击提交按钮时,Javascript和ajax就会被触发

    <html>
    <head>
        <title>Untitled Document</title>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
            $(function () {
            $('form').on('submit', function (e) {
            $.ajax({
            type: 'post',
            url: 'redirect.php',
            data: $('form').serialize(),
            success: function () {
            alert('form was submitted');     
            }
            });
            e.preventDefault();
            });
            });
        </script>
    </head>
    <body>
        <form>
            <div class="add_list">
                <p><span>Select User Name : </span>
                    <input type="text" name="username" size="20" />
                </p>
                <p><span>Select Your Password : </span>
                    <input type="password" name="password" size="20" />
                </p>
            </div>
            <div class="add_user">
                <input type="submit" value="add user" />
            </div>
        </form>
    </body>
</html>

在它被触发后,它加载这个页面,这个页面是重定向的。php页面

 <?php
include 'includes'config.php';
//connects to the database

if (!empty($_POST['username']) && !empty($_POST['password'])) {
    // Now checking user name and password is entered or not.
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    $check    = "SELECT * from user where username= '" . $username . "'";
    $qry      = mysql_query($check);
    $num_rows = mysql_num_rows($qry);
    if ($num_rows > 0) {
        // Here we are checking if username is already exist or not.
        echo "The username you have entered already exist. Please try again with another  username.";
        echo ('<script type="text/javascript"> alert ("The username you have entered already    exist.            Please try again with another username.");</script>');
        exit;
    }
    // Now inserting record in database.
    $query = "INSERT INTO user VALUES ('','" . $username . "','" . $password . "')";
    //id,username and password
    mysql_query($query);
    echo "User Added Successfully";
    echo ('<script type="text/javascript"> alert ("The username is added successfully.");</script>');
    exit;
}
?>

现在的问题是,当我提交表单时,它会提醒表单已提交,但redirect.php中的实际javascript没有加载,也没有提醒,而且php的echo也不起作用,尽管它正在数据库中提交,另一个问题是,如果当一个人输入表单时,该用户名已经存在,则会发出警告,然后什么都没有,何时我检查它没有被提交,因为用户名已经存在,但javascript的echo或alert不起作用。

我推荐这样的东西:

在redirect.php页面上:

if($num_rows > 0){
     echo ("fail");
}
else {
     //your insert code
     echo ("success")
}

您的ajax成功应该是

success: function(data) {
    switch(data) {
         case 'fail':
              //fail code here
              alert ('That user already exists');
              //or simply alert (data);
              break;
         case 'success':
              //Success code here
              alert (data);
              break;
         default:
              //Error - invalid response from redirect
    }
}

看起来你想错了。redirect.php页面不是向用户显示用户名存在或不存在的页面。redirect.php页面将一条消息(或结果)发送回ajax函数。ajax函数作用于该消息。可以通过在success函数中放入一个变量来访问该消息,例如:success:function(var)然后测试变量的内容并对其执行操作。

为了演示它的工作原理并避免混淆,我建议您制作一个test_ajax.php页面。test_ajax.php页面的全部内容是:

 <?php
 echo('These are the ajax results');
 ?>

并将url和成功函数更改为

<script>
    $(function () {
        $('form').on('submit', function (e) {
        $.ajax({
        type: 'post',
        url: 'test_ajax.php',
        data: $('form').serialize(),
        success: function(var) {
        alert (var);
        }
        });
        e.preventDefault();
        });
    });
</script>

现在,当您提交时,它会提醒您"这是ajax结果"。一旦您了解了它的工作原理,就可以返回到您的redirect.php页面,并让ajax对响应进行操作,如其他答案中所述。

您正在返回结果,但您使用ajax的方式错误。

成功已经为您提供了结果,如果您想在结果中使用html,则需要将其应用于DOM。

显示response.php响应的HTML/JS应该是这样的:

<html>
  <head>
        <title>Untitled Document</title>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
          $(function () {
            $('form').on('submit', function (e) {
              $.ajax({
                type: 'post',
                url: 'redirect.php',
                data: $('form').serialize(),
                success: function (data) {
                  $('.result').html(data);
                }
              });
              $('.result').html('form was submitted');
              e.preventDefault();
            });
          });
        </script>
  </head>
  <body>
    <form>
      <div class="add_list">
        <p>
          <span>Select User Name : </span>
          <input type="text" name="username" size="20" />
        </p>
        <p>
          <span>Select Your Password : </span>
          <input type="password" name="password" size="20" />
        </p>
      </div>
      <div class="add_user">
      <input type="submit" value="add user" />
      </div>
      <div class="result">
      </div>
    </form>
  </body>
</html>

您实际上有一些问题,但不会全部讨论。

首先,这只是一个建议,而不是编码错误,您应该使用mysqlliPDO进行数据库查询。您正在使用的mysql_函数不再受支持。

此外,(再次,只是咨询)你有这条线的地方:

"SELECT * from user where username= '" . $username . "'"

返回所有列只是为了计数是毫无意义的。只需使用SELECT username FROM user...SELECT COUNT(username) FROM user...。如果您曾经拥有许多列和数百万用户,那么这是一种很好的做法。如果您需要选中一列,然后选择一列,不要全部返回。

在您的PHP页面上,您可以简单地响应以下成功响应:

echo "Added";
// and //
echo "Exists";

您不需要用警报来回应脚本。您可以在客户端执行此操作。

您的AJAX请求可以有一个侦听器来响应:

$.ajax({
    type: 'post',
    url: 'redirect.php',
    data: $('form').serialize(),
    dateType: "html",
    success: function(data) {
        if (data == "Added") {
            alert("User added.");
        } elseif (data == "Exists") {
            alert("Username already exists!");
        } else {
            alert("User submission failed.");
        }  
    }, error: function() {
       alert("An error occurred.");
    }
});

例如,交换这段代码:

if ($num_rows > 0) {
    echo "The username you have entered already exist. Please try again with another  username.";
    echo ('<script type="text/javascript"> alert ("The username you have entered already    exist. Please try again with another username.");</script>');
    exit;
}

有了这个:

if ($num_rows > 0) {
    echo "Exists";
    exit;
}

并使用上面我描述的AJAX方法。