2010-06-23 5 views
5
$(document).ready(function(){ 
//global vars 
var name = $("#username"); 
    var email = $("#email"); 


function usernameExists() { 
    $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) { 
     if(m==1) { 
    return false; 
    } else { 
    return true; 
    } 
    }); 
} 
}); 

Firebug muestra la respuesta correcta cuando esta función está siendo llamado, sin embargo, no devuelve nada ... (esto $ .get (...) la función ha sido probado fuera de la función usernameExists() pero sin las devoluciones y funcionó perfectamente).jQuery obtener la función para volver verdadero/falso

¿Cuál es el problema y cómo resolverlo?


 $(document).ready(function(){ 
    //global vars 
    var form = $("#register"); 
    var name = $("#username"); 
    var email = $("#email"); 

    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
       if(m==1) { 
        form.submit(function(){ return false; }); 
       } else { 
        form.submit(function(){ 
     if(validateName() & validateEmail() & validatePass1() & validatePass2()) 
      return true 
     else 
      return false; 
       }); 
      } 

     } 
    ); 

function validateName(){ 
     // some check here 
    } 

// and other functions 

}); 

Respuesta

8

La función que está llamando no devuelve nada.

Incluso si intentara devolver la respuesta desde su $.get(), no funcionaría porque la llamada es asincrónica, por lo que cuando se recibió la respuesta, el código que hubiera utilizado el valor de retorno probablemente ya ejecutado.

Lo que debe hacer es llamar a su código desde la devolución de llamada $.get().

function usernameExists() { 
    $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) { 
      someOtherFunction(m==1); 
    }); 
} 

function someOtherFunction(parameter) { 
    // The parameter will be true or false 
    // depending on the value of m==1 
} 

actualizada en base a su comentario.

Probablemente es mejor llevar el $.get() al , pero manteniendo su idea original, así es como podría verse.

form.submit(function(){ 
     // After usernameExists() is called, we need to hand off 
     // the rest of the execution to that function since 
     // this one will be done executing before the get() 
     // response is received 
    usernameExists(); 
    return false; 
}); 

function usernameExists() { 
    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
       if(m==1) { 
        // do something if true 
       } else { 
        // do something if false 
       } 
      } 
    ); 
} 

Explicación de las alegrías de JavaScript asíncrono síncrono vs.

código Javascript normalmente ejecuta de forma sincrónica. Eso solo significa que se ejecuta una línea a la vez, o una línea debe terminar de ejecutarse antes de que la siguiente línea pueda disparar.

var greeting = "hi there"; // set the greeting variable 

alert(greeting); // the alert won't fire, 
        // until the previous line finished successfully 

Esto hace las cosas muy agradables y predecibles. Pero hay algunas excepciones a esa regla. Una excepción notable son las llamadas AJAX.

Su $.get() es un ejemplo de una llamada AJAX. La "A" en AJAX significa asincrónico, lo que significa que no impide la ejecución de la siguiente línea de código.

La ramificación es que cuando se hace una $.get() que toma (por ejemplo) 1 segundo para completar, cualquier código que se produjo después de la $.get() ha terminado de tiempo desde el momento en el $.get() ha recibido su respuesta.

Tome el ejemplo anterior greeting, pero esta vez usando AJAX.

var greeting; // will hold the response from our AJAX call 

$.get('some/path/to/data.php', 
     function(m) { 
      greeting = m; // populate the greeting variable with the data returned 
     } 
); 

alert(greeting); // Will alert "undefined" instead of the data that was returned 
        // because the $.get() code above is asynchronous, which allows 
        // the code below it (the alert in this case) to continue 
        // executing. 

Como se puede ver, el alert(greeting) habría ejecutado mucho antes de que se recibió la respuesta $.get(), porque $.get() es asíncrona, y no se detiene la cadena de ejecución mientras se está a la espera de sus datos.

Para resolver esto, usted debe colocar el alert()dentro la devolución de llamada para $.get(), de modo que no se ejecutará hasta que se recibe la respuesta.

var greeting; // will hold the response from our AJAX call 

$.get('some/path/to/data.php', 
     function(m) { 
      greeting = m; // populate the greeting variable with the data returned 
      alert(greeting); // Now the alert will give the expected result 
           // because it is in the callback. 
     } 
); 

El resultado es que en su código, una vez que se llama a $.get(), cualquier código restante que se basa en la respuesta recibida debe tener lugar dentro de la devolución de llamada.

La única manera de colocar el código fuera de la devolución de llamada sería colocarlo en su propia función que es llamada desde el interior la devolución de llamada (como lo hice con mi respuesta original).


Disposición básica de cómo el código debe operar:

tener en cuenta, que no necesariamente tienen una función separada para usernameExists(). Se podría colocar todo ese código dentro de la @cthulhu submit()

form.submit(function() { 
     // Check to make sure input is valid **before** you send the AJAX 
    if(validateName() & validateEmail() & validatePass1() & validatePass2()) { 
     usernameExists(); // If valid, continue with the usernameExists() 
    } 
    return false; // We return false whether or not the content was valid, 
        // in order to prevent the form from submitting prematurely 
}); 

function usernameExists() { 
    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
        // If "m" is less than one, there were no existing users 
        // so we can go ahead and post the data to the server 
       if(parseInt(m) < 1) { 
        // Here, you would need to manually do a post to 
        // submit the data to the server 
        $.post(url, data, callback, datatype); 
       } 
      } 
    ); 
} 

http://api.jquery.com/jquery.post/

+1

- Eso no funcionará porque 'usernameexists()' no devuelve nada. Y si lo hiciera, la instrucción 'if()' en su 'submit()' se ejecutará antes de que se reciba la respuesta. Básicamente, lo que debe hacer es mantener * cualquier código * que dependa de la respuesta de su '$ .get()' dentro de la devolución de llamada. O llame a otra función desde dentro de la devolución de llamada, como mi respuesta. Actualizaré mi respuesta con otra solución. – user113716

+0

@cthulhu - Debe comprender, * no * debe intentar devolver un valor de la función 'usernameExists()'. Simplemente no funcionará. Debe hacer el resto de la ejecución del código * dentro de esa función. Si no entiende por qué es así, hágamelo saber, y me complacería darle un ejemplo diferente que pueda explicar mejor. – user113716

+0

@cthulhu - No hay problema. : o) Actualizaré mi respuesta en unos minutos con un ejemplo en la parte inferior que describe más completamente el problema. – user113716

Cuestiones relacionadas