【问题标题】:Getting "SyntaxError: JSON.parse: unexpected character" When aparently the response is correct获取“SyntaxError:JSON.parse:意外字符”当显然响应正确时
【发布时间】:2014-03-18 18:58:48
【问题描述】:

我对这个错误很着迷,我正在准备制作一个 Ajax 登录表单,这是我的代码:

我的 HTML:

         <div id='login-box' name='login-box' class='radius-all-tiny'>
            <div class='bt-wrapper bt-wrapper-hover'>
                <span class='bt-icon bt-icon-hover btn-users'></span>
            </div>
            <div id='login-banner' name='login-banner'>
                " . $content['SESSION_BANNER'] . "
            </div>
            <div class='radius-all-tiny' id='login-error' name='login-error'>
                &nbsp;
            </div>
            <form id='login-frm' name='login-frm' method='post' action='./'>
                <input type='text' id='usuario' name='usuario' placeholder='" . $content['SESSION_USER'] . "' />
                <input type='password' id='contrasena' name='contrasena' placeholder='" . $content['SESSION_PASS'] . "' />
                <div class='submit-wrap'><input class='bt-submit radius-all-medium' type='submit' id='enviar' name='enviar' value='" . $content['CONTACT_FRM_SEND'] . "' /></div>
            </form>
        </div>

我的 JS:

        <script type='text/javascript'>
        $(document).ready(function() {
            // FORCE BROWSER NOT CACHE AJAX CALLS
            $.ajaxSetup({ cache: false });

            // HIDE ERROR DIALOG
            $('#login-error').hide();

            // LOGIN/OUT BUTTON BEHAVIOR
            $('#bt-login').click(function(){
                $('#login-error').hide();
                $.fancybox.open({
                    href : '#login-box',
                    padding : 0,
                    onClosed : function() { }
                });
            });

            // LOADING ANIMATION
            var ajaxload = '<img src=\"../img/components/spinner-dark.gif\" alt=\"" . $content['MAIN_LOADING'] . "\" />';

            $('#login-frm').bind('submit', function(){
                // AUTHENTICATING...
                // VALIDAMOS QUE NO HAYAN CAMPOS VACÍOS
                if (($('#usuario').val().length < 1) || ($('#contrasena').val().length < 1))
                {
                    $('#login-error').html('EMPTY');
                    $('#login-error').show();
                    return false;
                }

                // SI NO ESTÁN VACÍOS LOS CAMPOS, ENTONCES VALIDAMOS...
                $.ajax({
                    type: 'POST',
                    cache: false,
                    url: '../libs/class.log.in.out.php',
                    data: {usuario: $('#usuario').val(), contrasena: $('#contrasena').val()},
                    dataType: 'json',
                    success: function(data)
                        {
                            if (data.success)
                            {
                                // ESCRIBIMOS LA VARIABLE DE SESIÓN
                                // CERRAMOS FANCYBOX
                                $.fancybox.close();
                                // RECARGAMOS LA PÁGINA PRINCIPAL
                                document.location.href = $('#urlactual');
                            }
                            else
                            {
                                // MOSTRAMOS ERROR DE AUTENTICACIÓN
                                $('#login-error').html('FAILED_AUTH');
                                $('#login-error').show();
                            }
                        }
                });
                return false;
            });
        });
        </script>

我的class.log.in.out.php:

/////////////////////////////////////////////////
// TRANSPORTADOR DE DATOS
/////////////////////////////////////////////////
$data = array(
    'success' => false,
    'msg' => 'No se encontró ningún dato...'
);

// SOLICITAMOS LOS VALORES DE CONEXIÓN
$usr     = (isset($_REQUEST['usuario']) ? $_REQUEST['usuario'] : 'NULL');
$pwd     = (isset($_REQUEST['contrasena']) ? $_REQUEST['contrasena'] : 'NULL');

// VALIDAMOS LOS DATOS
class_exists('Database') || require ('class.database.php');
$resp = "";
$thisstt = false;
// INSTANCIAMOS LA CLASE DE BASE DE DATOS
$dbs = new Database();
$datos = $dbs->logIn($usr, $pwd, "", $thisstt);

if ($thisstt)
    $resp = $datos['usuario'];
else
    $resp = "" . $datos['error'] . " Usuario: " . $usr . "";

// DEVOLVEMOS EL ESTADO DE LA VALIDACIÓN
$data = array(
    'success' => $thisstt,
    'msg' => utf8_encode($resp)
);

/////////////////////////////////////////////////
// EMPAQUETADO DE DATOS
/////////////////////////////////////////////////
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data);

我收到来自 de class.log.in.out.php 的回复(使用 Firefox 的开发者工具):

认证失败时:

{"success":false,"msg":"Los datos ingresados son wrongos... Usuario: 123"}

认证正确时:

{"成功":true,"msg":"gchinchilla"}

但是 Firefox 说语法不正确,你能帮帮我吗?

我为我糟糕的英语道歉,我正在学习它......

【问题讨论】:

  • 我忘了说我用的是jQuery 1.11.0,我也试过1.10.2版本,但是报同样的错误...
  • 已解决!出现“编码错误”,我已将 PHP 文件从 UTF-8 转换为没有 BOM 的 UTF-8。

标签: ajax json


【解决方案1】:

我认为不需要将数组转换为 json_encode 的对象。

我会建议使用:

echo json_encode($data);

而不是:

echo json_encode((object)$data);

【讨论】:

  • 感谢@sumit 的回复,在更改为“echo json_encode($data);”后,我得到了相同的“语法错误”
【解决方案2】:

已解决!出现“编码错误”,我已将 PHP 文件从 UTF-8 转换为 UTF-8 without BOM。

更多信息在这里:http://es.wikipedia.org/wiki/UTF-8#Byte_order_mark_.28BOM.29

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2019-01-26
    • 2016-08-28
    相关资源
    最近更新 更多