简体   繁体   English

单击链接后插入一个值以配置Ajax功能

[英]Inserting a value to configure Ajax function upon clicking a link

I'm trying to set a function that makes an Ajax call, but I must confess I can't understand what's happening when I set the onclick event. 我正在尝试设置一个进行Ajax调用的函数,但是我必须承认,设置onclick事件时我无法理解正在发生的事情。 I'm trying to make an Ajax call to get fields from a database and display them to the user. 我正在尝试进行Ajax调用,以从数据库获取字段并将其显示给用户。 The idea is that the users type a Last Name in an input field, and then, depending on the link they click on, the function I'm trying to build displays the results of a query to the database. 这个想法是,用户在输入字段中键入一个姓氏,然后根据他们单击的链接,我尝试构建的功能将查询结果显示到数据库中。 I handle the query with a switch statement in PHP on the script that the Ajax function calls, but I can't set the variable that handles this behavior on the Javascript code. 我在Ajax函数调用的脚本上使用PHP中的switch语句处理查询,但无法在Javascript代码上设置处理此行为的变量。

I've got the Javascript code like this: 我有这样的Javascript代码:

var ajaxRequest = ajaxFunction();
function ajaxFunction(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
} return ajaxRequest;
} 

function process() {
id="default";
profesional = document.getElementById('profesional');
dotal = document.getElementById('dot'); 
proyecta = document.getElementById('proy');
proyecta_A = document.getElementById('proy_af');
gastosM = document.getElementById('gastos_med');
autos = document.getElementById('aut');
polifam = document.getElementById('polif');

profesional.onclick=function() {
id="prof";
return id;  
}
dotal.onclick=function() {
id="dotal";
return id;  
}
proyecta.onclick=function() {
id="proyecta";  
return id;
}
proyecta_A.onclick=function() {
id="proyAf";
return id;  
}
gastosM.onclick=function() {
id="gastos_medicos";
return id;  
}
autos.onclick=function() {
id="autos"; 
return id;
}
polifam.onclick=function() {
id="polifam";
return id;  
}   
if(ajaxRequest.readyState==4 || ajaxRequest.readyState==0) {apellido =     encodeURIComponent(document.getElementById('query').value)
if (apellido != undefined) {
ajaxRequest.open("GET", 'adminsrc.php?buscarregistro=' +apellido +'&id='+id, true)
ajaxRequest.send("");   
ajaxRequest.onreadystatechange=handleServerResponse;
}
}
else setTimeout('process()',1000);
}

function handleServerResponse(){
{
if (ajaxRequest.readyState==4) {

if(ajaxRequest.status==200) {   
respuesta=ajaxRequest.responseXML;
respuestadoc = respuesta.documentElement;
if (apellido != undefined) {
ident = respuesta.getElementsByTagName('identidad')[0];
result = ident.firstChild;
refrescar = respuesta.getElementsByTagName('identidad')[1];
actualizar = refrescar.firstChild;
if(result!=undefined) {
resultado = result.data;
document.getElementById('profesreg').setAttribute('value', resultado);
document.getElementById('dotalreg').setAttribute('value', resultado);
document.getElementById('gmmreg').setAttribute('value', resultado);
document.getElementById('proyectareg').setAttribute('value', resultado);
document.getElementById('proyecta2reg').setAttribute('value', resultado);
document.getElementById('autosreg').setAttribute('value', resultado);
document.getElementById('polifreg').setAttribute('value', resultado);
}
if(actualizar!=undefined) {
actualiza = actualizar.data;
document.getElementById('actual_1').setAttribute('value', actualiza);
document.getElementById('actual_2').setAttribute('value', actualiza);
document.getElementById('actual_3').setAttribute('value', actualiza);
document.getElementById('actual_4').setAttribute('value', actualiza);
document.getElementById('actual_5').setAttribute('value', actualiza);
document.getElementById('actual_6').setAttribute('value', actualiza);
document.getElementById('actual_7').setAttribute('value', actualiza);
}
msje = respuestadoc.firstChild.childNodes[0]; 
if (msje !=undefined) {
mess = msje.data;
document.getElementById("res").innerHTML = "<h4>"+ mess +"</h4>";
} 
     }
    setTimeout('process()',1000);
    }
    else alert ('hubo un problema al conectarse con el servidor: ' +    ajaxRequest.statusText);
}
}
} 

//-->

Where the last part is just to set the value of hidden fields in the form so that PHP recognizes those values (they are set to update some fields in the database). 最后一部分只是在表单中设置隐藏字段的值,以便PHP识别这些值(它们被设置为更新数据库中的某些字段)。 But I must say I'm pretty stuck with the javascript (I've never been good at it). 但我必须说,我非常喜欢javascript(我从不擅长于此)。 Any suggestions, please? 有什么建议吗?

@Mate The xml file is built like so: @Mate xml文件的构建方式如下:

<identificacion>
<response>
Se encontró al asegurado con nombre Mara Fernanda Bravo Palomino, número de póliza        27608165, la cual vence el 2003-04-05 y cuyos beneficiarios contratados son Ana Camila Lpez       Bravo
</response>
<identidad>Bravo Palomino</identidad>
<identidad>si</identidad>
</identificacion>

And once (a few weeks ago) I already had it working with a function like so: 一次(几周前),我已经使用了如下功能:

 function process() {
    if(ajaxRequest.readyState==4 || ajaxRequest.readyState==0) {apellido =        encodeURIComponent(document.getElementById('query').value)
    if (apellido != undefined) {
    ajaxRequest.open("GET", 'adminsrc.php?buscarregistro=' +apellido, true)
    ajaxRequest.send("");   
    ajaxRequest.onreadystatechange=handleServerResponse;
    }
    }
    else setTimeout('process()',1000);
    }

and the function handleServerResponse above; 和上面的handleServerResponse函数; but as you can see I can only extract the text nodes from the xml with that complicated iteration. 但是如您所见,我只能通过复杂的迭代从xml中提取文本节点。 Surely there's an easier way. 当然,有一种更简单的方法。

1) Download jQuery Library and link to te correct path !! 1)下载jQuery库并链接到正确的路径!

2) I'm a bit blind with html and xml response, but I think you can solve well. 2)我对html和xml响应有点盲目,但我认为您可以解决。

        <script src="jquery-1.8.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">

            function AjaxCall(id) {

                //Obtengo el appelido.
                var apellido = $('#query').val();

                //Armo la url con el querystring
                var urlPhp = 'adminsrc.php?buscarregistro=' + apellido + '&id=' + id;

                $.ajax({
                    type: "GET",
                    url: urlPhp,
                    contentType: "charset=utf-8",
                    dataType: "xml",
                    success: function (xml) {
                        successProcess(xml);
                    },
                    error: function (msg) {
                        alert("error");
                    }
                });
            }

            //Proceso el xml si estuvo Ok.
            function successProcess(xml) {
                //Revisar bien el XML devuelto

                var identidades = $(xml).find("identidad");

                result = identidades[0];
                refresh = identidades[1];
                message = $(xml).find('mensaje');

                SetResult(result);
                SetActualizar(refresh);
                SetMsj(message);

            }

            //Seteo el resultado en los valores de los controles.
            function SetResult(resultado) {

                if (result != undefined) {
                    $('#profesreg').val(resultado);
                    $('#dotalreg').val(resultado);
                    $('#gmmreg').val(resultado);
                    $('#proyectareg').val(resultado);
                    $('#proyecta2reg').val(resultado);
                    $('#autosreg').val(resultado);
                    $('#polifreg').val(resultado);
                }
            }

            //Seteo los dato actualizados
            function SetActualizar(actualiza) {
                if (actualiza != undefined) {
                    $('#actual_1').val(actualiza);
                    $('#actual_2').val(actualiza);
                    $('#actual_3').val(actualiza);
                    $('#actual_4').val(actualiza);
                    $('#actual_5').val(actualiza);
                    $('#actual_6').val(actualiza);
                    $('#actual_7').val(actualiza);
                }
            }

            //Muestro el mensaje
            function SetMsj(msje) {

                if (msje != undefined) {
                    $('#res').html("<h4>" + msje + "</h4>");
                }
            }


            //Este evento se dispara cuando carga el documento.
            $(document).ready(function () {

                $('#profesional').click(function () { AjaxCall('prof') });
                $('#dot').click(function () { AjaxCall('dotal') });
                $('#proy').click(function () { AjaxCall('proyecta') });
                $('#proy_af').click(function () { AjaxCall('proyAf') });
                $('#gastos_med').click(function () { AjaxCall('gastos_medicos') });
                $('#aut').click(function () { AjaxCall('autos') });
                $('#polif').click(function () { AjaxCall('polifam') });

            });


        </script>
    </head>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM