Domanda

Ho una funzione in javascript che prima controlla se il nome utente è la lunghezza desiderata e poi invia il nome utente ad una pagina per un test se il test è un successo ci sarà un <span id="username">true</span> altro <span id="username">false</span>

Continuo a ricevere un errore che getElementById non esiste sui dati di ritorno

  function checkuser(user, wd,id, sub)
    {
        if(user.length < 7)
        {
            document.getElementById(id).innerHTML = "Your username is too short. It must be longer than 6 charaters";
            document.getElementById(sub).disabled = true;
            return false;
        } else {
            $.post(wd + "register/checkuser/" + user,
                       function(data){
                         alert("Data Loaded: " + data.getElementById('username').innerHTML;
                       });
        }
    }
È stato utile?

Soluzione

Si deve fare questo:

function checkuser(user, wd, id, sub) {
  if(user.length < 7) {
    $("#"+id).html("Your username is too short. It must be longer than 6 characters");
    $("#"+sub).attr("disabled", true);
    return false;
  }
  else {
    $.post(
      wd + "register/checkuser/" + user,
      function(data){
        alert("Data Loaded: " + $(data).find("#username").html());
      }
    );
  }
}

Altri suggerimenti

Il valore restituito data è una stringa, non un DOMDocument -. Quindi non ha una funzione membro getElementById

Una migliore idea sarebbe quella di avere la vostra pagina di ritorno di prova JSON, invece, e analizzare quello.

Se non è possibile modificare la pagina che fa il test / ritorno, allora avrete bisogno di trovare un altro modo per analizzare la stringa di ritorno che serve i vostri scopi.

Prova questo:

   function(data){
       alert( "Data Loaded: " + $('#username', data).html() );
   });

O questo, a seconda della struttura del codice HTML restituito:

   function(data){
       alert( "Data Loaded: " + $(data).filter('#username').html() );
   });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top