La función fetch
Recuperando archivos txt
fetch('datos.txt')
.then(response => response.text())
.then(textString => {
console.log(textString);
});
.then(response => response.text())
.then(textString => {
console.log(textString);
});
Puede que aparezca el error: «URL scheme must be «http» or «https» for CORS request.» en consola.
Esto se debe a que el archivo .html debe estar alojado servidor web que sirva los archivos mediante HTTP o HTTPS para que la API Fetch funcione correctamente.
Si abres el .html desde el explorador de archivos, tu navegador esta cogiendo los archivos directamente desde el sistema de archivos.
Recuperando archivos csv
fetch('datos.csv')
.then(response => response.text())
.then(csvString => {
const rows = csvString.split('\n');
for (row of rows) {
console.log(row.split(","));
}
});
.then(response => response.text())
.then(csvString => {
const rows = csvString.split('\n');
for (row of rows) {
console.log(row.split(","));
}
});
Utilizando XMLHttpRequest
Enviando datos al servidor
var myXHR = new XMLHttpRequest();
myXHR.open("POST", "http://matoleot.ddns.net/dwec/ajax_php/valida_post_csv_xml_json.php", true);
myXHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
myXHR.onreadystatechange = function() {
if (myXHR.readyState == 4 && myXHR.status == 200) {
console.log("Recibida respuesta con Header completo: " + myXHR.getAllResponseHeaders());
document.getElementById('resultado').innerHTML = myXHR.responseText;
}
}
myXHR.send('csv,usuario,contraseña');
myXHR.open("POST", "http://matoleot.ddns.net/dwec/ajax_php/valida_post_csv_xml_json.php", true);
myXHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
myXHR.onreadystatechange = function() {
if (myXHR.readyState == 4 && myXHR.status == 200) {
console.log("Recibida respuesta con Header completo: " + myXHR.getAllResponseHeaders());
document.getElementById('resultado').innerHTML = myXHR.responseText;
}
}
myXHR.send('csv,usuario,contraseña');
Enviar los datos según el formato:
// CSV
datos = 'csv,' + nombre + "," + clave;
// XML
datos = "<datos><dato>xml</dato><dato>" + nombre + "</dato><dato>" + clave + "</dato></datos>";
// JSON
datos = {
lenguaje: 'json',
usuario: nombre,
clave: clave
};
datos = JSON.stringify(datos);
datos = 'csv,' + nombre + "," + clave;
// XML
datos = "<datos><dato>xml</dato><dato>" + nombre + "</dato><dato>" + clave + "</dato></datos>";
// JSON
datos = {
lenguaje: 'json',
usuario: nombre,
clave: clave
};
datos = JSON.stringify(datos);
Recibiendo datos del servidor
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Comprobar que nos llega un JSON
if (myXHR.getResponseHeader("Content-Type") == "application/json") {
let respuesta = JSON.parse(myXHR.responseText); // JSON
}
// Comprobar que nos llega un XML
if (myXHR.getResponseHeader("Content-Type") == "application/xml") {
let respuesta = myXHR.responseXML; // XML
}
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Comprobar que nos llega un JSON
if (myXHR.getResponseHeader("Content-Type") == "application/json") {
let respuesta = JSON.parse(myXHR.responseText); // JSON
}
// Comprobar que nos llega un XML
if (myXHR.getResponseHeader("Content-Type") == "application/xml") {
let respuesta = myXHR.responseXML; // XML
}
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();