-5

当我不使用数据库中的用户名和密码时,我的代码有效。但是,如果我确实匹配了数据库中的详细信息,那将是一个问题。但是,如果我在脚本中匹配它们,它就可以工作。怎么了?我希望代码在不刷新的情况下显示成功消息,并且在它重定向到 view.php 之后:它按原样工作,但是如果我集成与 php 匹配的数据库,那么 jquery 将继续告诉我错误的用户名或密码密码和用户名没问题

<script type="text/javascript">
$(document).ready(function() {

$("#login").click(function() {

    var action = $("#form1").attr('action');
    var form_data = {
        username: $("#username").val(),
        password: $("#password").val(),
        is_ajax: 1
    };

    $.ajax({
        type: "POST",
        url: action,
        data: form_data,
        success: function(response)
        {
            if(response == 'success')
                $("#form1").slideUp('slow', function() {
                //function to direct 

window.location.replace("view.php");
                //$("#message").html("<p class='success'>You          logged in successfully!</p>");
                });
            else
                $("#message").html("<p class='error'  style='color:red'>Invalid username and/or password.</p>");    
        }
    });

    return false;
});
// Function that redirects the user to another page
});
</script>

PHP 文件如果是这样的话,它会很好用。

<?php

    $is_ajax = $_REQUEST['is_ajax'];
    if(isset($is_ajax) && $is_ajax)
{
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];

    if($username == 'demo' && $password == 'demo')
    {
        echo "success"; 
    }
}

?>

与 db 匹配的 php 代码

<?php

$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username =(isset($_POST['username']))? trim($_POST['username']): '';
$password=(isset($_POST['password']))? $_POST['password'] : '';

// 
$query ='SELECT username FROM site_user WHERE '.
'username="'.mysql_real_escape_string($username,$con).'" AND ' .
'password = md5("'.mysql_real_escape_string($password,$con).'")';
$result=mysql_query($query,$con) or die (mysql_error($con));
if(mysql_num_rows($result)>0){
echo 'ok';
}

}
?>  
4

2 回答 2

1

首先,该url:参数没有获取 URL……但还有其他问题。

以此为例(借用此处的另一个问题/答案... jQuery Ajax POST 示例与 PHP

/* get some values from elements on the page: */
var values = $(this).serialize();

/* Send the data using post and put the results in a div */
$.ajax({
  url: "test.php",
  type: "post",
  data: values,
  success: function(){
      alert("success");
       $("#result").html('submitted successfully');
  },
  error:function(){
      alert("failure");
      $("#result").html('there is error while submit');
  }   
});
于 2013-01-16T16:02:06.793 回答
0

将正确的值传递给 ajax 函数

$.ajax({
        type: "POST",
        url: your php file handling form data,
        data: serialize the form data,
        success: function(response){}

});
于 2013-01-16T15:54:34.990 回答