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

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论