How Can I Request A Webpage That Is A .txt File?
I would like to retrieve the page data from a webserver in which the URL is http://www.xxxx.com/data.txt Is there a way with client side javascript to do this? Does the webserver
Solution 1:
You can't really do this in client side Javascript because of CORS. If the server you are requesting the data from supports CORS you can do it client side. However if the server you are requesting the data from does not support CORS you need to do the request server side and send it client side.
I would do this server side in a Node app and then fetch the data from your HTML page from the Node app. Here is a little node script to do it.
var express = require("express"),
app = express(),
request = require("request");
var port = process.env.VCAP_APP_PORT || 8080;
app.listen(port);
app.get("/data", function (req, res) {
request.get("http://www.xxxx.com/data.txt").pipe(res);
});
And then with JQuery on the client side you could do the following.
$.get("/data", function(data) {
console.log(data);
});
Solution 2:
In pure javascript :
var requestFile = newXMLHttpRequest();
requestFile.open('GET', 'http://www.xxxx.com/data.txt');
requestFile.onload = function() {
// Here's your text file content ie. requestFile.responseTextconsole.log(requestFile.responseText);
};
// Retrieve the text file
requestFile.send();
Or with jQuery
$.get('http://www.xxxx.com/data.txt', function(data) {
console.log(data);
});
Post a Comment for "How Can I Request A Webpage That Is A .txt File?"