简体   繁体   English

XMLHTTPRequest加载

[英]XMLHTTPRequest Loading

I am struggling with loading in text from a simple text file using XMLHTTPRequest API. 我正在努力使用XMLHTTPRequest API从一个简单的文本文件中加载文本。

Here is a list of technologies I am using in my development: 这是我在开发中使用的技术列表:

  • Microsoft Visual Studios 2010 Microsoft Visual Studios 2010
  • Microsoft Internet Explorer 8 Microsoft Internet Explorer 8

Overview: I am running a simple index.htm page that calls a script via an input type of 'Button'. 概述:我正在运行一个简单的index.htm页面,该页面通过“按钮”的输入类型调用脚本。 The API is allocated a reference in memory from the JavaScript and the function 'onReadyStateChange' is executed when the API state changes. 向API分配了JavaScript中内存中的引用,并且在API状态更改时执行了“ onReadyStateChange”功能。

A ready state of 1 (loading) was return and no status was returned. 返回就绪状态1(正在加载),没有状态返回。 No more instances of this function was called indicating to me that the state did not change there after. 不再调用此函数的实例,这向我表明状态此后没有发生变化。

Hint: I am tempted to think it is something to do with the resource's location and the application running in the localhost mode apposed to on a registered website, but I just don't know. 提示:我倾向于认为这与资源的位置以及在注册网站上以本地主机模式运行的应用程序有关,但我只是不知道。

HTML Code: HTML代码:

<body>
<input type="button" id="getSome"  title="Andrew Graham" value="Bob" onclick="Get_ListTextFile();"/>

<script src="Scripts/index.js" type="text/javascript"></script>

</body>

JavaScript Code: JavaScript代码:

var request= new XMLHttpRequest();

function Get_ListTextFile() {


    var uniformResourceLocator = 'Bob.txt';

    if (window.XMLHttpRequest = true) {

        request.open('GET', uniformResourceLocator,true);
        request.onReadyStateChange = ServerResponse();
        request.send();

    }

}

function ServerResponse() {

    var response;

    if (request != 'undifined') {

        if(request.readyState === 4 && request.status === 200){

            response = JSON.parse(request.responseText);

        }

    }

}

Webpage Request: http://*ls:1920/index.htm 网页请求:http:// * ls:1920 / index.htm

*ls = localhost * ls =本地主机

Contents of File: 文件内容:

Bob 1 Bob 2 Bob 3 鲍勃1鲍勃2鲍勃3

You on ready state change function should be in lowercase: 您在就绪状态更改功能上应小写:

request.onreadystatechange = ServerResponse();

Here is an updated version which is a little more reusable: 这是更新的版本,可重用:

var request = new XMLHttpRequest();

function load(url, callback) {
    if (window.XMLHttpRequest = true) {
        request.open('GET', url, true);
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status === 200) {
                callback(request.responseText);
            }
        }
        request.send();
    }
}

load('/', function(data) {
    console.log(data);
});

http://jsfiddle.net/p6H2r/ http://jsfiddle.net/p6H2r/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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