2012-03-19 14 views
5

Estoy intentando completar un elemento <select> a través de Ajax. Funciona muy bien en FF, pero obtengo un unknown runtime error en IE.innerHTML para <script> funciona en FF, no IE

HTML:

<select id="emp_select" name="emp_select"> 
    <option value=" ">Please enter a store</option> 
</select> 

Javascript:

$("#store").blur(function() { 
    populateDropdowns(); 
}); 

... 

function populateDropdowns() { 
     var store = $("#store").val(); 

     if (store.length != 4) { 
      alert("Store # must be 4 digits!"); 
      $("#store").focus(); 
      return false; 
     } 

     var xhrJSON = new XMLHttpRequest(); 
     var xhrEmpSelect = new XMLHttpRequest(); 
     var xhrMgrSelect = new XMLHttpRequest(); 

     var jsonDone = false; 
     var empSelectDone = false; 
     var mgrSelectDone = false; 

     $("#processing-dialog").dialog({ 
       width: 300, 
       height: 150 
     }); 

     xhrJSON.onreadystatechange = function() { 
      if (xhrJSON.readyState == 4) { 
       if (xhrJSON.status == 200) { 
        var js = document.createElement('script'); 
        js.type = 'text/javascript'; 

        js.innerHTML = xhrJSON.responseText; 
        var scr = document.getElementsByTagName('script')[1]; 
        scr.parentNode.insertBefore(js,scr); 

        jsonDone = true; 
        if (jsonDone && empSelectDone && mgrSelectDone) { 
         $("#processing-dialog").dialog("close"); 
         $("#processing-dialog").dialog("destroy"); 
         return true; 
        } 
       } else { 
        return false; 
       } 
      } 
     } 

     xhrEmpSelect.onreadystatechange = function() { 
      if (xhrEmpSelect.readyState == 4) { 
       if (xhrEmpSelect.status == 200) { 
        $("#emp_select").html(xhrEmpSelect.responseText); 
        empSelectDone = true; 
        if (jsonDone && empSelectDone && mgrSelectDone) { 
         $("#processing-dialog").dialog("close"); 
         $("#processing-dialog").dialog("destroy"); 
         return true; 
        } 
       } else { 
        return false; 
       } 
      } 
     } 

     xhrMgrSelect.onreadystatechange = function() { 
      if (xhrMgrSelect.readyState == 4) { 
       if (xhrMgrSelect.status == 200) { 
        $("#mgr_select").html(xhrMgrSelect.responseText); 
        mgrSelectDone = true; 
        if (jsonDone && empSelectDone && mgrSelectDone) { 
         $("#processing-dialog").dialog("close"); 
         $("#processing-dialog").dialog("destroy"); 
         return true; 
        } 
       } else { 
        return false; 
       } 
      } 
     } 

     var url = "ajax.cgi"; 

     var JSONdata = "action=generateJSON&store=" + store; 
     var EmpSelectData = "action=generateEmpSelect&store=" + store; 
     var MgrSelectData = "action=generateMgrSelect&store=" + store; 

     xhrJSON.open("POST",url); 
     xhrJSON.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
     xhrJSON.send(JSONdata); 

     xhrEmpSelect.open("POST",url); 
     xhrEmpSelect.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
     xhrEmpSelect.send(EmpSelectData); 

     xhrMgrSelect.open("POST",url); 
     xhrMgrSelect.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
     xhrMgrSelect.send(MgrSelectData); 
    } 

El manejador blur llama a una función para rellenar (todos) los diferentes elementos selectos, además de un objeto JavaScript que contiene una matriz asociativa de todo el empleados para hacer coincidir un nombre con una identificación de empleado que se devuelve como los valores de las opciones en ambos elementos select.

XHR texto devuelto (por xhrJSON, Content-Type = application/json):

var empArray = new Array({ id:"12345678", title:"The Title", code:"C123", name:"John Doe"},...); 

XHR texto devuelto por (xhrEmpSelect, Content-Type = text/html):

<option value=" ">Select One</option> 
<option value="John Doe">John Doe</option> 
<option value="Joe Blow">Joe Blow</option> 
... 
<option value="other">Other...</option> 
</select> 

Se devuelve texto similar para xhrMgrSelect, content-type = text/html

Por lo tanto, en FF todo funciona muy bien, el objeto JS aparece y se inserta en el DOM y ambos elementos <select> son poblado también. PERO en IE, obtengo un unknown runtime error en el controlador xhrJSON.onreadystatechange donde trato de configurar el js.innerHTML en el xhrJSON.responseText.

¿Qué estoy haciendo mal?

+2

¡Yikes! Si está utilizando jQuery, debe usar las rutinas .Ajax: haga que su vida sea más fácil en estos problemas de la plataforma x. – Hogan

+0

Nunca he tenido buena suerte con $ .ajax (¡y nunca me molesté en solucionarlo! Lo sé, lástima de mí ... :-( – daniel0mullins

+2

no tiene nada que ver con * suerte * –

Respuesta

5

Intente utilizar js.text = xhrJSON.responseText; en lugar de innerHTML. Creo que el problema que está teniendo tiene que ver con el hecho de que no puede insertar HTML en un bloque <script>.

+0

Este fue el claro ganador. 'innerText' y' textContent' no funcionó para mí. Ni tampoco 'setText (texto)'. Gracias @pseudosavant! – daniel0mullins

0

Como está configurando el script, debe usar innerText en lugar de innerHTML. Prueba esto.

js.innerText = xhrJSON.responseText; 
//Since FF do not sussport innerText but it does support textContent 
js.textContent = xhrJSON.responseText; 

Yo aconsejaría a migrar su código de jQuery que será mucho más simple, legible y fácil de mantener, sin ningún tipo de preocupaciones de soporte de los navegadores cruz. jQuery hace todo por ti.

0

Para definir el contenido de un objeto HTMLScriptElement, (creados con document.createElement('script');) se debe utilizar el método del objeto setText lugar de tratar de establecer el innerHTML del guión.

js.setText(xhrJSON.responseText); 

Consulte la especificación W3 desde el enlace de arriba.

Cuestiones relacionadas