doubi12138 2019-07-24 13:28
浏览 113

Ajax在这种情况下不起作用,我不知道为什么

I'm trying to receive some data as json from a php file, the php seems to be good and the html too, but te jquery file doesn't do the .done function and I can't find why. The Jquery version that I use is 3.1.0, and I'm using bootstrap for styles but I think it isn't important.

The HTML file:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registro Chat</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1>Chat 2.0</h1>
<div class="container col-md- mt-4">
    <form id="formulario">
      <div class="form-group">
        <label for="usuario">Nombre de Usuario</label>
        <input type="text" class="form-control" id="usuario" aria-describedby="emailHelp" placeholder="Introduzca el nombre de usuario">
        <p id="p-usuario"></p>
      </div>
      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Introduzca su email">
        <p id="p-email"></p>
      </div>
      <div class="form-group">
        <label for="contra1">Contraseña</label>
        <input type="password" class="form-control" id="contra1" aria-describedby="emailHelp" placeholder="Introduzca una contraseña">
        <p id="p-contra1"></p>
      </div>
      <div class="form-group">
        <label for="contra2">Repita la Contraseña</label>
        <input type="password" class="form-control" id="contra2" placeholder="Repita su contraseña">
        <p id="p-contra2"></p>
      </div>
      <button type="submit" class="btn btn-success bg-success">Enviar</button>
      <a href="principal.html"><button type="button" class="btn btn-success bg-success">Inicio de Sesión</button></a>
    </form>
</div>  
<script src="//code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="accionregistro.js"></script>
</body>
</html>

The JQuery file:

$(document).ready(principal);

function principal(){

$('#formulario').submit(runAjax);
}

function runAjax(event){

var enviados = {
    'usuario' : $('#usuario').val(),
    'email' : $('#email').val(),
    'contra1' : $('#contra1').val(),
    'contra2' : $('#contra2').val()
    };

$.ajax({
    type        : 'POST',
    url         : 'backendregistro.php',
    data        : enviados,
    dataType    : 'json',
    encode      : true  
})
.done(function(datos){
    alert();

    if(datos.exito){
            alert();
            $('0#p-usuario').text(datos.mensaje);
    }else{
        if(datos.error.vacio){
                alert(datos.error.vacio);
                //$('#p-usuario').text(datos.error.vacio);
        }
        if(datos.error.usuario){
                $('#p-usuario').text(datos.error.usuario);
        }
        if(datos.error.email){
                $('#p-email').text(datos.error.email);
        }
        if(datos.error.notmatch){
                $('#p-contraseña1').text(datos.error.notmatch);
        }
        }

});
event.preventDefault();
}

PHP file:

<?php  
$error=array();
$datos=array();

if(empty($_POST['usuario'])||empty($_POST['contra1'])||empty($_POST['contra2'])||empty($_POST['email'])){
    $error['vacio']="No puede haber campos en blanco";
}else{
    echo
        $usuario = $_POST['usuario'].
        $email = $_POST['email'].
        $contraseña1 = $_POST['contra1'].
        $contraseña2 = $_POST['contra2'];
}
//definimos la conexion a la base de datos
$mysqli = new mysqli('localhost','chat','chat2019','chat');

//comprobamos si el email ya existe
$mysqli -> query("select * from users where email='".$email."'");
if($mysqli->affected_rows!=0&&!empty($email)){
    $error['email']="Ese email ya está registrado";
} 
//comprobamos que no exista el usuario
$mysqli->query("select * from users where user='".$usuario."'");
if($mysqli->affected_rows!=0 && !empty($usuario)){
    $error['usuario']="Ya existe ese nombre de usuario";
}

//si no hay errores hacemos el insert
if(empty($error)){
    $datos['exito']=true;
    $datos['mensaje']="Usuario registrado correctamente";
    $mysqli->query("insert into users values ('".$usuario."','".$contraseña1."','".$email."')");
}else{
    $datos['exito']=false;
    $datos['error']=$error;
}

echo json_encode($datos);  

?>

When I try to see in the console if every thing is going well, it seems that the json is being sent but then the done function doesn't work. I'm soo noob at web programing, I know that probably the way I'm doing is very unsecure, but I only want to know why it doesn't works, thanks you.

  • 写回答

2条回答

  • douyousu9691 2019-07-24 13:34
    关注

    First of all as per jQuery doc, done callback is similar to success. So you have to try adding fail() and always() callbacks in order to determine response.

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?