ajax成功功能没有解雇

时间:2014-02-03 12:52:25

标签: php mysql sql ajax

我已经制作了一个使用php,ajax和mysql的登录表单,php代码似乎工作正常,因为它表示当输入用户凭据时,屏幕上会回显成功消息。

然而,ajax应该接受它并处理它并打开index.php页面,但它没有这样做。然而,当我的“检查...”消息按预期显示时,ajax确实起作用。任何帮助将不胜感激。请找到以下代码。

loginajax.js

function chk_ajax_login_with_php() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;


    var params = "username=" + username + "&password=" + password;
    var url = "login.php";
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'html',
        data: params,
        beforeSend: function () {
            document.getElementById("status").innerHTML = 'checking...';
        },
        complete: function () {

        },
        success: function (html) {
            if (html == "success") {
                window.location = 'index.php';
            }

        }

    });

}

的login.php

<?php

require "header.php"; 

 try 
{
    $connection = mysql_connect("localhost","root", "dbpassword");
    if(!$connection) {   
      die("Database connection failed: " . mysql_error());   
    }   
    $db_select = mysql_select_db("dbname",$connection);   
    if (!$db_select) {   
      die("Database selection failed:: " . mysql_error());   
     }   

   }catch (Exception $e){
     error_log(" DB Error: ".$e->getMessage());
   }

  if($_POST){

     $username=$_POST['username'];
     $password=$_POST['password'];
     $sql = mysql_query("SELECT * FROM usertable WHERE userID ='".$username."' AND  userPass ='".md5($password)."'") or die(mysql_error());
     $res=mysql_num_rows($sql);




 if($res>0){

     $rs_login=mysql_fetch_assoc($sql);
     $uid=$rs_login['user_id'];
     $_SESSION['sess_uid']=$uid;
     echo "success";

  } 

     else{

    echo "invalid username or password";

  }




  }

  ?>

4 个答案:

答案 0 :(得分:0)

你应该调试它!

success: function(html) {
      console.log(html);
      return false;
      //if(html=="success"){
      //window.location = 'index.php';
      //}
 }

在这里你将确保因为console.log而成功被激活,你会看到login.php输出。

答案 1 :(得分:0)

您是否包含jquery.js文件。 如果没有,请在标记

中包含以下行
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

答案 2 :(得分:0)

可能是错误的。

从jQuery 1.8开始,不推荐使用jqXHR.success(),jqXHR.error()和jqXHR.complete()回调。要准备最终删除的代码,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。

$.ajax( "example.php" )
 .done(function(html) {
     console.log(html);
 })
 .fail(function(html) {
     console.log(html);
 })
 .always(function(html) {
     console.log(html);
 });

答案 3 :(得分:0)

而不是html=="success",将其置于if条件中:

html.responseText=="success"

responseText以字符串格式包含服务器的响应。如果您不期望XML或JSON格式,则应始终使用responseText。

相关问题