javascript - Convert responseText object to string for alert - Stack Overflow

I am trying to get text from a .txt file, with Javascript. I am trying to test my code by using an aler

I am trying to get text from a .txt file, with Javascript. I am trying to test my code by using an alert statement to display the text from the file.

I am getting this alert box:

Here is my code:

$(document).ready(function() {
    // Obtain services text from .txt file
    var text = new XMLHttpRequest();
    text.open("GET", "js/servText.txt", true);
    text.onreadystatechange = function() {
        // Check states 4 = Ready to parse, 200 = found file
        if(text.readyState === 4 && text.readyState === 200) {
            text = text.responseText;
        }
    }
    alert(text);
    text.send(null);
});

I have tried to use JSON.stringify(); but I got an alert box with '{}' and it did not work in Google Chrome.

I also tried to use toString(); and String();

Any help would be great! Thanks -Chris

I am trying to get text from a .txt file, with Javascript. I am trying to test my code by using an alert statement to display the text from the file.

I am getting this alert box:

Here is my code:

$(document).ready(function() {
    // Obtain services text from .txt file
    var text = new XMLHttpRequest();
    text.open("GET", "js/servText.txt", true);
    text.onreadystatechange = function() {
        // Check states 4 = Ready to parse, 200 = found file
        if(text.readyState === 4 && text.readyState === 200) {
            text = text.responseText;
        }
    }
    alert(text);
    text.send(null);
});

I have tried to use JSON.stringify(); but I got an alert box with '{}' and it did not work in Google Chrome.

I also tried to use toString(); and String();

Any help would be great! Thanks -Chris

Share Improve this question asked Apr 19, 2013 at 16:29 Chris FrankChris Frank 4,4824 gold badges32 silver badges43 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You need to move your alert statement into the callback.:

$(document).ready(function() {
    // Obtain services text from .txt file
    var text = new XMLHttpRequest();
    text.open("GET", "js/servText.txt", true);
    text.onreadystatechange = function() {
        // Check states 4 = Ready to parse, 200 = found file
        if(text.readyState === 4 && text.status === 200) {
            alert(text.responseText);
        }
    }
    text.send(null);
});

AJAX calls are, as the name implies, Asynchronous. Your alert gets called immediatly, it doesn't wait for the AJAX request to plete.

Asynchronousness can be quite a mind boggle. Your code doesn't run from top to bottom but rather you have to look at the events. Where does an event start? what data do I have? etc.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745382267a4625281.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信