Solució exercici1-Ajax

De wikiserver
Dreceres ràpides: navegació, cerca

Fitxer Javascript:

var xhr;

function inici(){
    if (window.XMLHttpRequest) { //Tots els altres navegadors que soporten ajax
            xhr = new XMLHttpRequest();
    }
    else {
            throw new Error("Ajax is not supported by this browser");
    }
    
    xhr.open('GET', 'info.php');
    
    xhr.onreadystatechange = function() {
	if (this.readyState == 4) {
		if (this.status >= 200 && this.status < 300) {
			document.getElementById('content').innerHTML = this.responseText;
//La propiedad responseText se utiliza para tratar los datos recibidos desde el servidor que no tienen formato XML, podremos acceder a los datos siempre y cuando el estado de la conexión devuelto con readyStatechange sea igual a 3 (recibiendo) o 4 (a punto). 
//Siempre que podamos intentaremos usar responseXML en lugar de responseText y XML para la los datos en lugar de texto plano.
		}
	}
    }
    
    
    xhr.send(null);
    
    
}

window.onload = inici;

Fitxer HTML:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="exercici1.js"></script>
    </head>
    <body>
        <div id="content">TODO write content</div>
    </body>
</html>

Fitxer PHP:

<?php

echo phpinfo();
?>