[英]Load .txt from remote server
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. 我正在尝试从在另一台服务器上运行的javascript获取存储在我的一台服务器中的.txt
文件的内容。
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. 但是我在远程.txt
文件的第1行收到Uncaught SyntaxError: Unexpected identifier
。
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: 我的建议是创建一个使用curl来获取文件内容的php文件:
//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: 对于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 . 在我看来,如果您使用CORS 而不是jsonp,那么您就不需要花太多时间了 。
In PHP it seems to be as easy as adding something like this on the server side: 在PHP中, 看起来就像在服务器端添加这样的内容一样容易:
header("Access-Control-Allow-Origin: *");
Here is one last resource, for getting CORS working . 这是使CORS正常工作的最后一个资源。
Since you're not returing a json object, you should change your dataType to text. 由于您没有重现json对象,因此应将dataType更改为text。
$.ajax({
url: "http://example.com/file.txt",
dataType: "text",
success: function(data) { remoteFile = data; }
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.