Ajax不执行成功函数

Ajax does not execute success function

我有一个 jquery ajax 函数,可以将表单数据提交到 php 文件,并在其中对照数据库进行检查并 returns 响应。但是我的成功函数没有被执行,而是通过错误函数返回响应。

以下是我的login.js代码:

$(document).ready(function(){
    $("form#loginForm").submit(function() { // loginForm is submitted
        var username = $('#username').attr('value'); // get username
        var password = $('#password').attr('value'); // get password

    if (username && password) { // values are not empty
        $.ajax({
            type: "POST",
            url: "url", // URL of the Php script
            contentType: "application/json; charset=utf-8",
            dataType: "json", //expected from server in response
            // send username and password to the Php script
            data: "username=" + username + "&password=" + password,


            error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                + ", textStatus: " + textStatus
                + ", errorThrown: " + errorThrown);
                $('div#loginResult').addClass("error");
            },

            success: function(data){ //script was successful, data contains response from mysql database
                if (data.error) { // login was not successful
                    $('div#loginResult').text("data.error: " + data.error);
                    $('div#loginResult').addClass("error");
                } // if
                else { // login was successful
                    $('form#loginForm').hide();
                    $('div#loginResult').text("data.success: " + data.success);
                    $('div#loginResult').addClass("success");
                } //else
            } // success
        }); // ajax
    } // if
    else {
        $('div#loginResult').text("enter username and password");
        $('div#loginResult').addClass("error");
    } // else
    $('div#loginResult').fadeIn();
    return false;
});
});

这是我的Login.php代码:

 <?php



$username = $_POST["username"];
$password = $_POST["password"];


$dbhost = '*****';
$dbuser = '*****';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

echo 'Connected to database successfully,';

mysql_select_db('sl493',$conn); //pick sl493 database


$result = mysql_query("SELECT *
        FROM metauser
        WHERE metauser.username = '$username'
        AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table

$row = mysql_fetch_assoc($result);

if($row['username'] == $username) //If username and password not accepted
{$result = 'true login';
 $arr = array('success' => "login is successful");
 echo json_encode($arr);}

else //if username and password are not accepted
{$result = 'login failed';
 $arr = array('error' => "username or password is wrong");
 echo json_encode($arr);}

?>

现在,无论我输入的凭据是否正确,我都会收到以下响应:

responseText:已成功连接到数据库,{"success":"login is successful"} , textStatus: parsererror, errorThrown: Invalid JSON: 连接到数据库成功,{"success":"login is successful"} http://i.imgur.com/n1nZ2ac.jpg

它 returns "Connected to database successfully" 这意味着它成功地进入 login.php 但它也 returns responseText 这是 ajax:error 的一部分,它应该在哪里自从执行函数后就不会继续 successful.HALP ?

试试这个:

var data="";
data=['username':username,'password':password];//Add this

 $.ajax({
            type: "POST",
            url: "url", // URL of the Php script
            contentType: "application/json; charset=utf-8",
            dataType: "json", //expected from server in response
            // send username and password to the Php script
            data: JSON.stringify(data),//Stringify your data while sending
            success: function(data){ //script was successful, data contains response from mysql database
                if (data.error) { // login was not successful
                    $('div#loginResult').text("data.error: " + data.error);
                    $('div#loginResult').addClass("error");
                } // if
                else { // login was successful
                    $('form#loginForm').hide();
                    $('div#loginResult').text("data.success: " + data.success);
                    $('div#loginResult').addClass("success");
                } //else
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                + ", textStatus: " + textStatus
                + ", errorThrown: " + errorThrown);
                $('div#loginResult').addClass("error");
            }, // success
        }); // ajax

请将您的 ajax 数据类型从 dataType: "json" 更改为

datatype: "application/json"

要解决未经授权响应时的响应 header 问题,请在代码的其他部分添加响应 header 作为 header('HTTP/1.1 401 Unauthorized', true, 401);,如下所示。

else //if username and password are not accepted
{$result = 'login failed';
 $arr = array('error' => "username or password is wrong");
header('HTTP/1.1 401 Unauthorized', true, 401);
 echo json_encode($arr);} 

我发现哪里出了问题:

  1. 首先,我将 ContentType 指定为 json,同时我将其作为 字符串,所以我不得不更改它。

  2. 其次,我使用 Is_set andis_empty 函数为 $_POST 制作 确定我得到了 POST 个字段。

  3. 最后 return ajax 可变数据原因无法显示 按键,所以 data.success 未定义,但数据 return 是所有输出 来自 php 文件。

我仍在尝试弄清楚为什么我无法通过密钥访问 returned JSON。如果您有任何建议,请告诉我,我不会提出另一个问题。以下是工作代码:

$(document).ready(function(){
    $("form#loginForm").submit(function() {

    // loginForm is submitted
        var username = $('#username').attr('value'); // get username
        var password = $('#password').attr('value'); // get password
        console.log(username + password) ;

        if (username && password) { // values are not empty
            $.ajax({
                type: "POST",
                url: "https://xxx/login.php", // URL of the Php script
                contentType: "application/x-www-form-urlencoded; charset=utf-8",

                dataType: "application/json", //expected from server in response
                // send username and password to the Php script
                //data: "username=" + username + "&password=" + password,
                data:'username='+ username+'&password='+ password,

                error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                    $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                    + ", textStatus: " + textStatus
                    + ", errorThrown: " + errorThrown);
                    $('div#loginResult').addClass("error");
                },

                success: function(data){


                    $('form#loginForm').hide();
                    $('div#loginResult').text("Login: " + data );
                    $('div#loginResult').addClass("success");
                                                                }


            });
        }
        else {
            $('div#loginResult').text("enter username and password");
            $('div#loginResult').addClass("error");
        } // else
        $('div#loginResult').fadeIn();
        return false;
    });
})

;

Login.php

<?php

if (isset($_POST["username"]) && !empty($_POST["username"])) {
    $username = $_POST["username"];}

if (isset($_POST["password"]) && !empty($_POST["password"])) {
    $password = $_POST["password"];}

$dbhost = 'xxx';
$dbuser = 'xxxxxx';
$dbpass = 'xxxxxxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('sl493',$conn);

$query = mysql_query("SELECT *FROM metauser WHERE metauser.username = '$username'AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table
$row = mysql_fetch_assoc($query);


if($row['username'] == $username)
{
        if($row['usertype']== 'student')
              { $type = 'student'; }
                    else{ $type = 'admin'; }

    //$arr = array('result' => 'loginOK', 'usertype' => $type);

    $associativeArray = array();
    $associativeArray ['result'] = 'success';
    $associativeArray ['usertype'] = $type;

    //$arr = '{"success":"login is successful"}';
    //echo $type;
    echo json_encode($associativeArray); }


else
{$arr = '{"error":"username or password is wrong"}';
    echo json_encode($arr);}

?>