For example, there is a http://test.com/a.txt file.
['http://a.com', false],
['http://b.com', false],
['http://c.com', false],
['http://d', false]
I want to use this file as a var value like below:
<script>
...
var list = [ ***I want to get that .txt file as values here.*** ];
...
</script>
result
<script>
...
var list = [
['http://a.com', false],
['http://b.com', false],
['http://c.com', false],
['http://d', false]
];
...
</script>
How can I make it? I tried the javascript code below:
jQuery.get('http://test.com/a.txt', function(data) {
// The type o breaking line caracter will vary depending on OS
var values = data.split("\n");
var List = values[values.length-1];
});
But it didn't work...
If you're doing this on a page with the same origin as that file (see the Same Origin Policy), or if that file's server supports cross-origin requests from your site, you could easily parse it as JSON by wrapping it in [
and ]
and converting '
to "
:
jQuery.get('http://test.com/a.txt', function(data) {
var list = JSON.parse("[" + data.replace(/'/g, '"') + "]");
// ...
});
Naturally this assumes there are no '
inside the '
-quoted strings in the data.
If it's a cross-origin request that the server doesn't allow, you can't do it from a browser; you'd need to make the request to your own server and have your server request it from the other side.
Re your comment:
I just tried it but it didn't work. It shows an error message. Uncaught SyntaxError: Unexpected token ; in JSON at position 10233 at JSON.parse ()
Then the data isn't as you show in your question, because if it were, it would work:
var data =
"['http://a.com', false],\n" +
"['http://b.com', false],\n" +
"['http://c.com', false],\n" +
"['http://d', false]";
console.log("data:");
console.log(data);
console.log("parsed:");
var list = JSON.parse("[" + data.replace(/'/g, '"') + "]");
console.log(list);
.as-console-wrapper {
max-height: 100% !important;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments