2010-06-23 17 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 mostra la risposta giusta quando è chiamata questa funzione, tuttavia, non restituisce nulla ... (questo $ .get (...) la funzione è stato testato al di fuori della funzione usernameExists() ma senza i ritorni e ha funzionato perfettamente).jQuery arrivare funzione restituisca true/false

Qual è il problema e come risolverlo?


 $(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 

}); 

risposta

8

La funzione che si sta chiamando non restituisce nulla.

Anche se provasse a restituire la risposta dal tuo $.get(), non funzionerebbe perché la chiamata è asincrona, quindi nel momento in cui la eseguito.

Quello che devi fare è chiamare il tuo codice dalla callback $.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 
} 

aggiornato in base alle tuo commento.

Probabilmente meglio solo per portare lo $.get() nello submit(), ma restando fedele alla tua idea originale, ecco come potrebbe apparire.

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 
       } 
      } 
    ); 
} 

Spiegazione delle gioie sincrono rispetto Asynchronous JavaScript

codice JavaScript esegue normalmente sincrono. Significa solo che esegue una riga alla volta o che una riga deve terminare prima che la linea successiva possa sparare.

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

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

Questo rende le cose molto belle e prevedibili. Ma ci sono alcune eccezioni a questa regola. Un'eccezione degna di nota sono le chiamate AJAX.

Il tuo $.get() è un esempio di una chiamata AJAX. La "A" in AJAX sta per asincrono, il che significa che non impedisce l'esecuzione della prossima riga di codice.

la ramificazione è che quando si fa un $.get() che prende (per esempio) 1 secondo per completare, qualsiasi codice è venuto dopo la $.get() ha da tempo finito per il momento il $.get() ha ricevuto la sua risposta.

Prendere l'esempio precedente greeting, ma questa volta utilizzando 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. 

Come si può vedere, la alert(greeting) sarebbe eseguita lungo prima della ricezione della risposta $.get(), perché $.get() è asincrona, e non interrompere la catena di esecuzione mentre è in attesa per i suoi dati.

Per risolvere questo, si dovrebbe inserire il alert()all'interno il callback per $.get(), in modo che non verrà eseguito fino a quando viene ricevuto la risposta.

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. 
     } 
); 

Il risultato è che nel codice, una volta che si chiama $.get(), qualsiasi codice rimanente che si basa sulla risposta ricevuta dovrebbe avvenire all'interno la richiamata.

L'unico modo per inserire il codice di fuori la richiamata sarebbe quella di inserire nella sua propria funzione che viene chiamato da all'interno il callback (come ho fatto con la mia risposta originale).


Layout di base di come il vostro codice dovrebbe funzionare:

tenere a mente, che non hanno necessariamente bisogno di una funzione separata per usernameExists(). Si potrebbe inserire tutto ciò che il codice all'interno del 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

@cthulhu - Non funzionerà, perché 'usernameExists()' non restituisce nulla. E se accadesse, l'istruzione 'if()' nel tuo 'submit()' sarebbe eseguita prima che la risposta fosse ricevuta. Fondamentalmente, ciò che devi fare è mantenere * qualsiasi e * codice che si basa sulla risposta dal tuo '$ .get()' all'interno del callback. Oppure chiama un'altra funzione dall'interno del callback, come la mia risposta. Aggiornerò la mia risposta con un'altra soluzione. – user113716

+0

@cthulhu - Devi capire, tu * non devi * provare a restituire un valore dalla funzione 'usernameExists()'. Semplicemente non funzionerà. È necessario eseguire il resto dell'esecuzione del codice * all'interno * di quella funzione. Se non capisci perché è così, fammi sapere, e sarei felice di darti un esempio diverso che potrebbe spiegare meglio. – user113716

+0

@cthulhu - Non è un problema. : o) Aggiornerò la mia risposta in pochi minuti con un esempio in basso che descrive più dettagliatamente il problema. – user113716

Problemi correlati