I'm trying to get the content of a .txt
file stored in one of my servers from a javascript which run on another server.
I'm using:
$.ajax({
url: "http://example.com/file.txt",
dataType: "jsonp",
success: function(data) { remoteFile = data; }
});
But I get Uncaught SyntaxError: Unexpected identifier
at line 1 of the remote .txt
file.
The text file is something like:
----My document----
Once upon a time, there was a fat princess...
How can I fix this problem?
My suggestion is to create a php file that uses curl to get the contents of the file:
//getFile.php
<?php
if(isset($_GET['filename'])) {
$fName = $_GET['filename'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$text = curl_exec($ch);
echo $text;
}
?>
And for the jQuery:
$.ajax({
url : './getFile.php',
data : { filename : 'http://example.com/file.txt'},
success : function (r) { console.log(r) //your data }
})
It seems to me you wouldn't need to mess around as much if you used CORS instead of jsonp .
In PHP it seems to be as easy as adding something like this on the server side:
header("Access-Control-Allow-Origin: *");
Here is one last resource, for getting CORS working .
Since you're not returing a json object, you should change your dataType to text.
$.ajax({
url: "http://example.com/file.txt",
dataType: "text",
success: function(data) { remoteFile = data; }
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.