Ir para conteúdo
Fórum Script Brasil
  • 0

Minha Classe Ajax.


Splintter

Pergunta

Olá Pessoal, eu construi uma classe Ajax em Javascript, mas não sei por que ela não está funcionando.

Muito Estranho, no meu ver não há nada Errado,

alguém poderia Analizar este script?

//========================================================================
//= SigmaWeb - SigmaRO Website Portal System.
//========================================================================
//= Copyright (c) 2006 By Skulldiggers.
//= 
//= This program is free software. You can redistribute it and/or modify
//= it under the terms of the GNU General Public License as published by 
//= the Free Software Foundation; either version 2 of the License.
//========================================================================

var MyCounter = (new Date).getTime();

function GetHttpRequest(){
    var httpRequest = false;
    if (window.XMLHttpRequest){
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType)
            httpRequest.overrideMimeType('text/xml');
    }
    else if (window.ActiveXObject){
        try{
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
            try{
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){}
        }
    }
        return httpRequest;
}

function ParseResponse(MyText){
    // Parse Javascripts.
    while (MyText.indexOf("<script type=\"text/javascript\">") > -1) { // Found Javascript.
        var x        = MyText.indexOf("<script type=\"text/javascript\">") + "<script type=\"text/javascript\">".length;
        var y        = MyText.indexOf("</script>") - x;
        var TempTxT = MyText.substr(x, y);
        MyText.replace('/'+TempTxT+'/gi', ''); // Cut Off This Script.
        eval(TempTxT);
    }
    // Parse Alerts.
    while (MyText.indexOf("ALERT|") > -1) { // Found Alert.
        var x        = MyText.indexOf("ALERT|") + "ALERT|".length;
        var y        = MyText.indexOf("|ENDALERT") - x;
        var TempTxT = MyText.substr(x, y);
        MyText.replace('/'+TempTxT+'/gi', ''); // Cut Off This Alert.
        window.alert(TempTxT);
    }
    
    // Return TRUE if content is changed, else, return FALSE.
    if(MyText.length > 0) {
        return true;
    }
    
    return false;
}

// Creates a URL-encoded query to send as an XMLHttpRequest
function createQuery(form)
{
    var elements = form.elements;
    var pairs = new Array();

    for (var i = 0; i < elements.length; i++) {

        if ((name = elements[i].name) && (value = elements[i].value))
            pairs.push(name + "=" + encodeURIComponent(value));
    }

    return pairs.join("&");
}

function AjaxGet(http, div_name) { // Get Function
    // Create XMLHttpRequest Element.
    var XMLRequest = GetHttpRequest();
    if(!XMLRequest) return null;
    
    // Show Loading Div.
    document.getElementById('load_div').style.visibility="visible";
    
    //Put a Random String on Url.
    MyCounter++;
    if(http.indexOf("?") > -1) {
        http += "&rand=" + MyCounter;
    }
    else {
        http += "?rand=" + MyCounter;
    }
    
    // Open Connection with the document.
    XMLRequest.open("GET", http, true);
    XMLRequest.onreadystatechange = ParseRequest;
    XMLRequest.send(NULL);
    
    return true;
}
    
    
function AjaxPost(http, div_name, frm_id) { // Post Function.
    // Create XMLHttpRequest Element.
    var XMLRequest = GetHttpRequest();
    if(!XMLRequest) return null;
    
    // Show Loading Div.
    document.getElementById('load_div').style.visibility="visible";
    
    //Put a Random String on Url.
    MyCounter++;
    if(http.indexOf("?") > -1) {
        http += "&rand=" + MyCounter;
    }
    else {
        http += "?rand=" + MyCounter;
    }
    
    //Prepare Query.
    var query = createQuery(document.getElementById(frm_id));
    
    // Open Connection with the document.
    XMLRequest.open("POST", http, true);
    XMLRequest.onreadystatechange = ParseRequest;
    
    // Send Header and Query.
    XMLRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    XMLRequest.send(query);
    
    return true;
}

// Processes the information from a returned Request
function ParseRequest(){
    // Just do it on State 4(Done)
    if(XMLRequest.readyState == 4) {
        // Hide Loading.
        document.getElementById('load_div').style.visibility="hidden";
        //Parse Response Text, and print it.
        var Response = XMLRequest.responseText;
        if(ParseResponse(Response)) {
            document.getElementById(div_name).innerHTML = Response + ' ';
        }
    }
}

// Swap Visibility of some Elements.
function SwapField(fieldvalue) {
    if(fieldvalue == "none") {
        document.getElementById('link_field01').style.visibility="visible";
        document.getElementById('link_field02').style.visibility="visible";
    }
    else {
        document.getElementById('link_field01').style.visibility="hidden";
        document.getElementById('link_field02').style.visibility="hidden";
    }
}

function SetCookie (name, value) {  
    var argv     = SetCookie.arguments;  
    var argc     = SetCookie.arguments.length;  
    var expires = (argc > 2) ? argv[2] : null;  
    var path     = (argc > 3) ? argv[3] : null;  
    var domain     = (argc > 4) ? argv[4] : null;  
    var secure     = (argc > 5) ? argv[5] : false;  
    document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) +  ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}

Se alguém puder me ajudar, sou grato.

Há, Caso consigua fazer isto funcionar, Eu estou Autorizando a Utilizar, Desde que mantenha o Copyright.

Link para o comentário
Compartilhar em outros sites

8 respostass a esta questão

Posts Recomendados

  • 0

na linha:

while (MyText.indexOf("<script type=\"text/javascript\">") > -1) { // Found Javascript.
pode ser interpretado errado pelo navegador. Separe a string ;)
while (MyText.indexOf("<sc"+"ript type=\"text/javascript\">") > -1) { // Found Javascript.
na linha:
var x        = MyText.indexOf("<script type=\"text/javascript\">") + "<script type=\"text/javascript\">".length;
você usou o .length diretamente, assim pode causar erro. O "<script" pode ser interpretado errado. separe a string. ;)
var x        = MyText.indexOf("<scr"+"ipt type=\"text/javascript\">") + ("<sc"+"ript type=\"text/javascript\">").length;
Na linha:
var y        = MyText.indexOf("</script>") - x;
O "</script>" pode não ser interpretado direito também.
var y        = MyText.indexOf("</scr"+"ipt>") - x;
na linha:
var x        = MyText.indexOf("ALERT|") + "ALERT|".length;
Não use o .length direto na string.
var x        = MyText.indexOf("ALERT|") + ("ALERT|").length;

Tenta agora, diz a resposta a ok? :)

Link para o comentário
Compartilhar em outros sites

  • 0

To sim,

O erro eu não sei, uso o Firefox, mas o debugger que eu instalei n mostra nada.

Muito estranho, Pois a função antiga minha funciona.

function LINK_ajax(http, div_name) { //Link Functions

    var LINK_xmlhttp = false;

    try { 
        LINK_xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
    }
    catch (e) {
        try {
            LINK_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        }
        catch (e) {
            try {
                LINK_xmlhttp = new XMLHttpRequest();
            }
            catch (e) {
                LINK_xmlhttp = false; 
            }
        }
    }
    if (!LINK_xmlhttp) return null;
    
    document.getElementById('load_div').style.visibility="visible";

    LINK_xmlhttp.open("GET", http, true);

    LINK_xmlhttp.onreadystatechange = function() {
        if (LINK_xmlhttp.readyState == 4) {
            document.getElementById('load_div').style.visibility="hidden";

            if (LINK_xmlhttp.responseText.indexOf("<script type=\"text/javascript\">") > -1) {
                var x        = LINK_xmlhttp.responseText.indexOf("<script type=\"text/javascript\">") + "<script type=\"text/javascript\">".length;
                var y         = LINK_xmlhttp.responseText.indexOf("</script>") - x;
                eval(LINK_xmlhttp.responseText.substr(x, y));
            }
            
            if (LINK_xmlhttp.responseText.indexOf('ALERT|') > -1) {
                var x = LINK_xmlhttp.responseText.indexOf('ALERT|') + "ALERT|".length;
                var y = LINK_xmlhttp.responseText.indexOf('|ENDALERT') - x;
                window.alert(LINK_xmlhttp.responseText.substr(x , y));
            } else {
                document.getElementById(div_name).innerHTML = LINK_xmlhttp.responseText + ' ';
            }
        }
    }

    LINK_xmlhttp.send(null);  

    return false;
}

Akela outra classe ficou melhor, só falta funcionar xD

Link para o comentário
Compartilhar em outros sites

  • 0

Erro: NULL is not defined

Linha: 95

function AjaxGet(http, div_name) { // Get Function
    // Create XMLHttpRequest Element.
    var XMLRequest = GetHttpRequest();
    if(!XMLRequest) return null;
    
    // Show Loading Div.
    document.getElementById('load_div').style.visibility="visible";
    
    //Put a Random String on Url.
    MyCounter++;
    if(http.indexOf("?") > -1) {
        http += "&rand=" + MyCounter;
    }
    else {
        http += "?rand=" + MyCounter;
    }
    
    // Open Connection with the document.
    XMLRequest.open("GET", http, true);
    XMLRequest.onreadystatechange = ParseRequest;
    XMLRequest.send(NULL); // Linha 95
    
    return true;
}

O que há de errado ai?

Ah, tenho mais uma duvida

No meu código antigo, as palavras vem assim oh

Em vez de Menu do usuário:, aparece Menu do usu�rio:

alguém sabe como arrumar isso?

Obrigado.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...