我使用XMLHttpRequest作为菜单,当我请求一个包含javascript的页面HTML时,没有任何反应,为什么

I use XMLHttpRequest for a menu and when i request a page HTML that contains javascript inside it nothing happens,why?

本文关键字:HTML javascript 为什么 任何反 包含 XMLHttpRequest 菜单 请求 一个      更新时间:2023-09-26
这是我在网页

中用于菜单的代码,在某些情况下,我想要请求的页面中包含javascript,但是当请求的页面加载到实际页面时,脚本不会运行。

//Ajax menu permite uma ligação de cada vez
    var ajaxIsOcup = false;
    function ajaxDo(file,divdoID,appendDiv,thinkinotherdiv,reqTyp ,datastring) {
        if(ajaxIsOcup == false) {
            // Variáveis com default
                if (appendDiv === undefined || appendDiv === '') appendDiv = false;
                if (reqTyp === undefined || reqTyp === '') reqTyp = "POST";
                if (datastring === undefined || datastring === '') datastring = null;
                if(thinkinotherdiv === undefined || thinkinotherdiv === '') thinkinotherdiv = null;
            // End Variáveis com default
            ajaxIsOcup = true;  // Ocupar função ajax
            // Verifica em qual elemento insere a imagem de processo e insere-a
                var divtoThink = "";
                if(thinkinotherdiv == null) divtoThink = document.getElementById(divdoID);
                else divtoThink = document.getElementById(thinkinotherdiv);
                deleteElementById("ajaxDoErrThinking");
                divtoThink.innerHTML += "<div style='background-color: white;' id='ajaxDoThinking'><img src='imagens/system/thinking.gif' style='width: 100px; height: 100px;' /></div>"; 
            // End Verifica em qual element insere a imagem de processo e insere-a
            var xmlhttp = null;    
            // Construção do objeto XMLHttpRequest segundo o tipo de navegador   
            if (window.ActiveXObject && !window.XMLHttpRequest){
                window.XMLHttpRequest = function(){
                    progIds=new Array("Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
                    for(i in progIds){
                            try{
                                return new ActiveXObject(progIds[i]);
                            }catch(ex){
                                console.log(progIds[i]);
                            }
                    }
                    return null;
                };
            }else if(window.XMLHttpRequest)    
                xmlhttp = new XMLHttpRequest();    
            else {    
                // XMLHttpRequest não é suportado pelo navegador    
                alert("Seu navegador não suporta os objetos XMLHTTPRequest...");  
                ajaxIsOcup = false;  // Desocupar função ajax
                deleteElementById("ajaxDoThinking");
                deleteElementById("ajaxDoErrThinking");
                return;    
            }  
            // End Construção do objeto XMLHttpRequest segundo o tipo de navegador   
            function ErrShowing() {
                deleteElementById("ajaxDoThinking");
                if(datastring == null) var tmpdatastring = "";
                else tmpdatastring=datastring;
                var temps = ['"'+file+'"','"'+divdoID+'"',appendDiv,'"'+thinkinotherdiv+'"','"'+reqTyp+'"','"'+tmpdatastring+'"'];
                if(!document.getElementById("ajaxDoErrThinking")) divtoThink.innerHTML += "<div onclick='ajaxDo("+temps[0]+","+temps[1]+","+temps[2]+","+temps[3]+","+temps[4]+","+temps[5]+");' style='cursor: pointer; background-color: red;' id='ajaxDoErrThinking'><p style='cursor: pointer; margin: 0;'>Erro a carregar a página, verifique a sua ligação á internet e clicque aqui para tentar novamente!</p>";
                xmlhttp.abort();
                document.getElementById(divdoID).innerHTML = "";
                ajaxIsOcup = false;  // Desocupar função ajax
            }
            xmlhttp.open(reqTyp,file,true);
            // Verifica o estado do request e responde quando o mesmo concluir o processo de GET
                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                        clearTimeout(xmlhttpTimeout);
                        if(appendDiv == true) document.getElementById(divdoID).innerHTML += xmlhttp.responseText;
                        else document.getElementById(divdoID).innerHTML = xmlhttp.responseText;
                        deleteElementById("ajaxDoThinking");
                        deleteElementById("ajaxDoErrThinking");
                        ajaxIsOcup = false;  // Desocupar função ajax
                    }else if(xmlhttp.readyState==4 && xmlhttp.status==404) {
                        clearTimeout(xmlhttpTimeout);
                        ErrShowing();
                    }
                }
            // End Verifica o estado do request e responde quando o mesmo concluir o processo de GET
            xmlhttp.setRequestHeader('Content-Type', 'charset:UTF-8'); //Define o tipo de encode
            xmlhttp.send(datastring); //Envia o pedido
            // Timeout to abort in 5 seconds
            var xmlhttpTimeout=setTimeout(function() {ErrShowing();},5000);
        }
    }

我发现了问题!!问题不在于XMLHttpRequest,而在于内部HTML的专有性!

为了解决这个问题,我更改了一些代码,它是这样的:

            xmlhttp.onreadystatechange=function() {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    clearTimeout(xmlhttpTimeout);
                    if(appendDiv == true) document.getElementById(divdoID).innerHTML += xmlhttp.responseText;
                    else document.getElementById(divdoID).innerHTML = xmlhttp.responseText;
                    deleteElementById("ajaxDoThinking");
                    deleteElementById("ajaxDoErrThinking");
                    ajaxIsOcup = false;  // Desocupar função ajax
                }else if(xmlhttp.readyState==4 && xmlhttp.status==404) {
                    clearTimeout(xmlhttpTimeout);
                    ErrShowing();
                }
            }

事情是这样的:

                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                        clearTimeout(xmlhttpTimeout);
                        var answer = xmlhttp.responseText;
                        var divtodo = document.getElementById(divdoID);
                        var evalloadEl = document.createElement("div");
                        evalloadEl.innerHTML = answer;
                        var arr = evalloadEl.getElementsByTagName('script');
                        for (var n = 0; n < arr.length; n++) {
                                eval(arr[n].innerHTML)
                            }
                        if(appendDiv == true) divtodo.innerHTML += answer;
                        else divtodo.innerHTML = answer;
                        deleteElementById("ajaxDoThinking");
                        deleteElementById("ajaxDoErrThinking");
                        ajaxIsOcup = false;  // Desocupar função ajax
                    }else if(xmlhttp.readyState==4 && xmlhttp.status==404) {
                        clearTimeout(xmlhttpTimeout);
                        ErrShowing();
                    }
                }

我必须使用 eval() 来运行在 innerHTML 的辅助下运行的代码。