简体   繁体   中英

reading txt file from url (javascript)

I'm trying to read .txt files from external links the user provides, so I can later use them in an app. For now I'm just trying to show them in a div (.output). I got so far, and now I got stuck, don't really know how to proceed.

 function getText(url){ var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(null); request.onreadystatechange = function () { if (request.readyState === 4 && request.status === 200) { var type = request.getResponseHeader('Content-Type'); if (type.indexOf("text") !== 1) { return request.responseText; } } } } $(".url-input").change(function() { getText($(".url-input").value); }); 
 .output { width:500px; height:500px; border: 1px solid black; } 
 <!DOCTYPE html> <html> <head> <title>Ugh</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="index.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="index.js"></script> </head> <body> <div class="output"></div> <input class="url-input" type="url"> </body> </html> 

JavaScript get (notice you have to input the file name with the extension (.txt): just change the value to val():

$(".url-input").change(function() {
    getText($(".url-input").val());
});

jQuery get: replace all the javascript with these few lines:

$(".url-input").change(function() {
    $.get($(this).val(), function( data ) {
        $('.output').html(data);
    });
});

This is much better option, because the Ajax Get is an asynchronous call, so you want to update the output value on the callback.

By the way, you should do some validation on that use input before you make the Ajax call. Also, to remove the need to add the ".txt" in the input change it to:

$(".url-input").change(function() {
    $.get($(this).val()+'.txt', function( data ) {
        $('.output').html(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM