активируемые JS функции после PHP + Ajax innerHTML не работает - PullRequest
1 голос
/ 22 декабря 2011

Во-первых: я не хочу использовать JQuery, я знаю, что это облегчит, но это изнасилует всю эту вещь. Примечание: ajaxFunction является примером ajax по умолчанию для GET / POST

Теперь, после нажатия на функцию, в первый раз она работает, и каждый заменяется php-echo. Проблема ПОСЛЕ.

После изменения initia-div («login-place») на следующий div («regit») функция javascript в sregit.onClick = function () не работает.

Как мне обойти это? Должен ли я создать DOMElement в PHP и использовать xmlSave ("index.php")?

начально-ДИВ:

<div id="login-place">
    <table id="login-init" name="login-init">
    <tr>
        <td>username</td>
        <td><input type="text" name="user" id="user" /></td>
        <td>password</td>
        <td><input type="password" name="pass" id="pass" /></td>
    </tr>
    <tr>
        <td colspan="2"><input name="login" id="login" type="button" value="entrar" /></td>
    </tr>
    </table>
</div>

код JS:

            var slogin = document.getElementById("login");
            slogin.onclick = function() {
                //alert("inside."+user.value);
                s = "goforth=1&user="+user.value+"&pass="+pass.value;
                ajaxFunction('4',""+s); 
            }

            var sregit = document.getElementById("regit");
            sregit.onclick = function () {
                alert("inside."+user.value);
                s = "regit=1&user="+user.value+"&pass="+pass.value;
                ajaxfunction('4',""+s); 
            }
    function ajaxFunction(arg,string) {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if(xmlhttp) {

          if (arg==4) {
            nextland = "login-place";
            document.getElementById("all-burps").innerHTML=string;
            xmlhttp.open("POST","session.php",true);
          }
        xmlhttp.onreadystatechange  = handleServerResponse;
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        if (arg==4) {
            xmlhttp.setRequestHeader('Content-length', string.length);
            xmlhttp.send(""+string); 
        }
        }
    }
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       if (nextland != "login-place") { document.getElementById(nextland).innerHTML=xmlhttp.responseText; } //Update the HTML Form element
       else {
           // alert(xmlhttp.responseText); -> this is true no error up here.
           var thediv = document.getElementById("login-init"); 
           thediv.parentNode.removeChild(thediv); //this happens fine.
           var theplace = document.getElementById("login-place");
           var thelement = document.createElement("div"); //this too.
           thelement.innerHTML=xmlhttp.responseText;  //this too'
           theplace.appendChild(thelement); //this too.

       }
     }

И, innerhtml.responseText = = 1015 *

        echo '
            <table id="login-2" name="login-2">
            <h3>o username ' . $username . ' não existe. <a href="#" id="register-link" name="register-link">Queres registar?</a></h3>
            <tr>
                <td>username</td>
                <td><input type="text" name="user" id="user" value="' . $username . '"/></td>
            <td>password</td>
                <td><input type="password" name="pass" id="pass" value="' . $password . '" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="button" value="entrar" id="regit" name="regit"/></td>
            </tr>
        </table>
        ';

Надеюсь, этого достаточно, чтобы кто-нибудь понял мои сомнения. иначе я перефразирую это.

Ответы [ 3 ]

2 голосов
/ 22 декабря 2011

Вызов в функции, которая не работает, говорит ajaxfunction, тогда как функция называется ajaxFunction - Javascript чувствителен к регистру.

Также вам необходимо переместить объявление onclickФункция для regit внутри функции handleServerResponse() после строки thelement.innerHTML=xmlhttp.responseText;, потому что до вызова этой строки нет элемента с id="regit", поэтому привязка функции не будет работать.

Кроме того, вы должны завершить функции, объявленные как element.onclick = function () {}, с помощью ;.Объявление функций таким способом является оператором присваивания , поэтому для его завершения требуется точка с запятой.

EDIT здесь ваш код переработан, так что, надеюсьчто вы хотите, с удаленным лишним вздутием живота.Я предполагаю, что xmlhttp, nextland, user и pass были объявлены в некотором коде, который вы не опубликовали - не так ли?

document.getElementById("login").onclick = function() {
  //alert("inside."+user.value);
  var s = "goforth=1&user="+encodeURIComponent(user.value)+"&pass="+encodeURIComponent(pass.value);
  ajaxFunction(4, s); 
};

function ajaxFunction(arg, string) {
  //var getdate = new Date();  //Used to prevent caching during ajax call
  // ...but never actually *used* anywhere...
  if (xmlhttp) {
    if (arg == 4) {
      nextland = "login-place";
      document.getElementById("all-burps").innerHTML = string;
      xmlhttp.open("POST", "session.php", true);
    }
    xmlhttp.onreadystatechange = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    if (arg == 4) {
      xmlhttp.setRequestHeader('Content-length', string.length);
      xmlhttp.send(string); 
    }
  }
}

function handleServerResponse() {
  var theplace, thelement;
  if (xmlhttp.readyState == 4) {
    if (xmlhttp.status == 200) {
      if (nextland != "login-place") {
        // Update the HTML Form element
        document.getElementById(nextland).innerHTML = xmlhttp.responseText;
      } else {
        // Remove the old div and add the new content
        theplace = document.getElementById("login-place");
        theplace.removeChild(document.getElementById("login-init"));
        thelement = document.createElement("div");
        thelement.innerHTML = xmlhttp.responseText;
        theplace.appendChild(thelement); //this too.
        // Now add the click handler
        document.getElementById("regit").onclick = function() {
          // alert("inside."+user.value);
          var s = "regit=1&user="+encodeURIComponent(user.value)+"&pass="+encodeURIComponent(pass.value);
          ajaxfunction(4, s); 
        };
      }
    } else {
      // Handle HTTP errors
      alert('HTTP ' + xmlhttp.status);
    }
  }
}
1 голос
/ 22 декабря 2011

Попробуйте вызвать

"sregit.onclick = function () {...."

после добавления содержимого в функцию handleServerResponse ().Когда вы вызываете его раньше, никакое действие не связывается, потому что в DOM нет элемента #regit.

0 голосов
/ 22 декабря 2011

События onClick теряются при таком изменении HTML.Вам придется повторно добавлять события onClick каждый раз, когда вы заменяете HTML или используете встроенный onClick, например onclick="something()".

. У вас также есть синтаксическая ошибка, вы используете строчную букву F в ajaxfunction('4',""+s);, тогда как функция называется ajaxFunction.

...