我正在尝试使用 php、jquery、ajax、json 创建一个登录系统,它会验证是否有空字段,但是一旦我完成并提交表单,ajax 调用就会失败,控制台会显示 json响应文本中的数组,所以问题不是php部分,而是它说parsererror,我不知道如何解决这个问题,我还是个菜鸟。这是我的代码:
索引.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>
验证器.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");
}
日志.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;
}
}
连接器.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: Object {readyState: 4, responseText: "{"fail":true,"messages":"El usuario aa no existe(the user aa doesn´t exist)</div>"}", status: 200, statusText: "OK"} ajax.js:54: parsererror
我从控制台得到这个:
语法错误:意外的标记 在 Object.parse( native ) 在 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 )
似乎我收到了一个格式错误的请求,这是我在另一个问题中读到的内容
最佳答案
看起来您正在点击 error()
ajax.js 第 54 行的回调和解析错误:
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)</div>
-- 这实际上是尾随 </div>
没有开口<div>
?
重要旁注:看起来您正在从请求值中获取原始用户输入并在以下语句中通过您的数据库运行它:"Select * from user where username = '{$user}'"
.这让您可以打开所谓的 SQL Injection attack。 .恶意攻击者可以使用它从您的数据库中删除数据或选择您不想公开的数据。您应该切换到使用 PDO + prepared statements或转义输入数据以防止这种情况。
关于javascript - 在 Ajax 调用中获取解析器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022834/