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.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?