The 'onreadystatechange' method of XMLHttpRequest is not executed

1

I have this code that I simplified to find out why it does not work, but I still can not find the error. I put a alert() after the onreadystatechange method and I checked that it never gets executed. Why can it be?

localhost / folder / http.html:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <script>

    function func(url){

        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange(function(){
            alert('Esto no se ejecuta nunca');

            if(xhr.readyState == 4 && xhr.status == 200){

               document.getElementById('div1').innerHTML = xhr.responseText;

            }
        });

        xhr.open("GET", url, true);
        xhr.send();
    }

    </script>
</head>


<body>
<div id="div1">div1</div>
<span style="cursor: pointer; text-decoration: underline"
    onclick="func('test.php?ptr=argumento')">
        Hacer una petición
</span>
</body>
</html>

localhost / folder / test.php:

<?php echo "GET = " . $_GET['ptr']; ?>
    
asked by N.N. 04.12.2018 в 05:12
source

1 answer

2

You must change the way you assign the ajax function, that is, do not place it in parentheses but assign it to the operator "=", as follows:

xhr.onreadystatechange = function(){
        alert('Esto no se ejecuta nunca');
        if(xhr.readyState == 4 && xhr.status == 200){
           document.getElementById('div1').innerHTML = xhr.responseText;
        }
    };
    
answered by 04.12.2018 / 05:26
source