最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Load .txt from remote server - Stack Overflow

programmeradmin2浏览0评论

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: ".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?

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./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?

Share Improve this question asked Sep 6, 2013 at 17:06 PurpleFoxyPurpleFoxy 1,1273 gold badges12 silver badges17 bronze badges 9
  • your file is not json. You have to proxified it server side if it is a cross domain request – A. Wolff Commented Sep 6, 2013 at 17:10
  • Try changing the dataType to "text". 'file.txt' isn't json. – Jon La Marr Commented Sep 6, 2013 at 17:11
  • @JonLaMarr but then cross domain error will be fired – A. Wolff Commented Sep 6, 2013 at 17:11
  • @A.Wolff exactly, I need JSONP for cross origin.. – PurpleFoxy Commented Sep 6, 2013 at 17:12
  • @user2070518 but a text file is not json valid, so, proxify it server side – A. Wolff Commented Sep 6, 2013 at 17:13
 |  Show 4 more ments

3 Answers 3

Reset to default 4

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./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./file.txt",  
   dataType: "text",  
   success: function(data) { remoteFile = data; }  
});  
发布评论

评论列表(0)

  1. 暂无评论