【问题标题】:Getting parsererror in Ajax Call在 Ajax 调用中获取解析器错误
【发布时间】:2016-07-01 13:47:41
【问题描述】:

我正在尝试使用 php、jquery、ajax、json 创建一个登录系统,它会验证是否有空字段,但是一旦我完成并提交表单,ajax 调用就会失败,控制台会显示 json响应文本中的数组,所以问题不是php部分,而是说parsererror,我不知道如何解决这个问题,我还是个菜鸟。这是我的代码:

index.php

<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="/ajax/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="/ajax/css/style.css"/>
        <meta charset="UTF-8">
    </head>
    <body>

        <section>
            <div class="container">
                <div class="row">
                    <div class="col-xs-12" id="titulo">
                        <h3>Ajax Login</h3>
                    </div>
                    <div class="col-xs-10 col-xs-offset-1">
                        <form id="formulario" action="php/validator.php" method="post">
                            <div class="col-xs-4 col-xs-offset-4" id="formPart">
                                <label for="user">Nombre de Usuario</label>
                                <input type="text" id="user" name="user" class="form-control">
                                <div class="user"></div>
                            </div>
                            <div class="col-xs-4 col-xs-offset-4" id="formPart">
                                <label for="pass">Nombre de Usuario</label>
                                <input type="password" id="pass" name="pass" class="form-control">
                                <div class="pass"></div>
                            </div>
                            <div class="col-xs-4 col-xs-offset-4" id="formPart">
                                <input type="submit" value="Iniciar Sesión" class="btn btn-success">
                            </div>
                        </form>
                        <div class="col-xs-4 col-xs-offset-4" id="response"></div>
                    </div>
                </div>
            </div>
        </section>


        <script src="/ajax/js/jquery2.js"></script>
        <script src="/ajax/js/bootstrap.min.js"></script>
        <script src="/ajax/js/ajax.js"></script>
        <script>

            $(document).ready(function(){

                setTimeout(function(){

                    $('#user').focus();

                }, 700);

            });

        </script>
    </body>
</html>

validator.php

<?php 

if($_POST){

    $required = array('user', 'pass');
    $validation = array('user' => 'Debes Ingresar tu Nombre de Usuario', 'pass' => 'Debes Ingresar tu Contraseña');
    $error = array();
    $inputs = array();

    foreach($required as $key){ 
        if(array_key_exists($key, $_POST)){
            if(empty($_POST[$key])){
                $error[$key] = $validation[$key];
            }
            else{
                $inputs[$key] = $_POST[$key];
            }
        }
        else{
            $error[$key] = $validation[$key];
        }
    }

    if(!empty($error)){     
        $array = array('error' => true, 'fields' => $error);
    }
    else{
        $user = $inputs['user'];
        include 'log.php';
        if(user($user)){
            $message = '<div class="alert alert-success">Bienvenido '.$inputs['user'].'</div>';
            $array = array('success' => true, 'message' => $message);
        }
        else{
            $messages = '<div class="alert alert-success">El usuario '.$inputs['user'].' no existe</div>';
            $array = array('fail' => true, 'messages' => $messages);
        }
    }
    header('Content-Type: application/json');
    echo json_encode($array);
}
else{
    header("Location: ../index.php");
}

log.php

<?php

function user($user){

    include 'conexion.php';
    $conexion = conectar();
    mysqli_set_charset($conexion, "utf8");


    $query = "Select * from user where username = '{$user}'";
    $result = mysqli_query($conexion, $query);
    $total = mysqli_num_rows($result);


    if($total > 0){

        return true;

    }
    else{

        return false;

    }

}

conexion.php

<?php 


function conectar(){

    error_reporting(0);

    $server = 'localhost';
    $user_db = 'root';
    $pass_db = '';
    $db = 'user';


    $conexion = new mysqli($server, $user_db, $pass_db, $db);

    if($conexion->connect_errno){

        echo 'Error de Conexion. Código de Error: '.$conexion->connect_errno;

    }
    else{

        return $conexion;

    }

}

ajax.js

$('#formulario').on('submit', function(){

    $('#formulario .warn').remove();
    $('form input').removeClass('warning');

    var thisForm = $(this),
        url = thisForm.attr('action'),
        type = thisForm.attr('method'),
        data = thisForm.serializeArray();


        $.ajax({

            url: url,
            type: type,
            data: data,
            dataType:"json",
            crossDomain: true,
            success: function(response){

                if(response.error){

                    $.each(response.fields, function(index, value){

                        $('.' + index).hide().html('<span class="warn">' + value + '</span>').fadeIn(700);
                        $('#' + index).addClass('warning');

                    });

                }

                else if(response.success){

                    $('#formulario').fadeOut(700, function(){

                        $('#response').hide().html(response.message).fadeIn(700);

                    });

                }

                else{

                    $('#response').hide().html(response.messages).fadeIn(700);

                }



            },
            error: function(xhr, textStatus){

                console.log(xhr);
                console.log(textStatus);

            }

        });


    return false;

});

我在控制台中收到以下错误:

ajax.js:53: 对象 {readyState: 4, responseText: "{"失败":true,"messages":"El usuario aa 不存在(用户 aa 不存在)

“}”,状态: 200, statusText: "OK"} ajax.js:54: parsererror


我从控制台得到这个:

SyntaxError: Unexpected token 在 Object.parse (本机) 在 n.parseJSON (http://localhost/ajax/js/jquery2.js:4:6225) 在 zb (http://localhost/ajax/js/jquery2.js:4:8172) 在 z (http://localhost/ajax/js/jquery2.js:4:11629) 在 XMLHttpRequest。 (http://localhost/ajax/js/jquery2.js:4:15507)

似乎我收到了格式错误的请求,这就是我在另一个问题中看到的内容

标签: javascript php jquery ajax


【解决方案1】:

看起来您在 ajax.js 的第 54 行遇到了 error() 回调和解析错误:

console.log(textStatus);

我们需要进入您的success 回调。返回给浏览器的 HTTP 状态码是什么?您可以使用 Chrome 工具或 Firebug 并查看浏览器中的响应来找到它。

您的响应 JSON 正文如下所示: { "fail": true, "messages": "El usuario aa no existe(the user aa doesn´t exist)</div>" }

messages 包含El usuario aa no existe(the user aa doesn´t exist)&lt;/div&gt;——这实际上是一个尾随&lt;/div&gt;,没有开头&lt;div&gt;

重要的旁注:看起来您正在从请求值中获取原始用户输入并在以下语句中通过您的数据库运行它:"Select * from user where username = '{$user}'"。这使您可以使用所谓的SQL Injection attack。恶意攻击者可以使用它从您的数据库中删除数据或选择您不想暴露的数据。您应该切换到使用PDO + prepared statements 或转义输入数据以防止这种情况发生。

【讨论】:

  • 是的,我遇到了错误部分,http 状态是 200,在 $message 中,div 有它的开始和结束标签,我不知道为什么开头没有出现,但是我去掉了 div 标签,得到了相同的结果,parsererror,你说得对,我只是在测试这个,我将使用 pdo,准备好的语句,绑定参数等等,但这只是一个测试
  • 出于调试目的,您能否按如下方式更新您的 ajax.js:jsfiddle.net/davemaple/psxaopup 并从控制台粘贴结果?
  • 成功回调 ajax.js:19 {"error":true,"fields":{"user":"Debes Ingresar tu Nombre de Usuario","pass":"Debes Ingresar tu Contraseña" }} ajax.js:22 错误回调 ajax.js:23 {"readyState":4,"responseText":"{\"fail\":true,\"messages\":\"El usuario asadasdsdasd no existe\" }","status":200,"statusText":"OK"} 填写表格时基本相同,触发错误部分
  • 好的。我现在明白了。在第二种情况下,它必须返回无效的 JSON。有什么方法可以查看 Firebug 或 Chrome 工具中的原始响应并截取响应正文的屏幕截图?另外——你能抓住所有返回的标题吗?
  • 如何上传截图?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多