简体   繁体   English

XMLHttpRequest-将responseText返回到另一个函数时,它返回未定义

[英]XMLHttpRequest - when returning responseText to another function, it returns undefined

SOLVED. 解决了。 I changed my code into this: 我将代码更改为此:

function init() {
    //preloadImages();
    getContent('events', 'events');
    getContent('content', 'main');
}

function loadingScreen(start) {
    var loadingSpan = document.getElementById('loading');
    if (start == true) {
            loadingSpan.innerHTML = '<p>Loading...<br><img src="images/loading.gif"></p>';
    }
    else {
            loadingSpan.innerHTML = '';
    }
}

function getContent(what, where) {
    if (what == 'content') {
            loadingScreen(true);
            var ranLoad = true;
    }
    var toSet = document.getElementById(what);
    var location = "content/" + where + ".txt";
    var request = new XMLHttpRequest;
    request.open("GET", location, true);
    request.onreadystatechange = function(){
            if (request.readyState == 4 && request.status == 200){
                    toSet.innerHTML = request.responseText;
                    if (ranLoad==true){
                            loadingScreen(false);
                    }
            }
    }
    request.send(null);
}
window.onload = init;

tl;dr or long-winded - see the code and the results below. tl; dr或long绕-请参阅下面的代码和结果。

So. 所以。 I am building a small webpage for a friend, and I decided to try out a technique where instead of writing the content directly in the webpage, I will use XMLHttpRequest to retrieve content (in the same domain), and place them in the content , where it will be updated by javascript, when people click on a different anchor. 我正在为一个朋友构建一个小型网页,所以我决定尝试一种技术,而不是直接在网页中编写内容,而是使用XMLHttpRequest检索内容(在同一域中)并将其放置在内容中,当人们单击不同的锚点时,将使用javascript进行更新。 Well, I came across a roadbump. 好吧,我遇到了一个障碍。 When I created the functions for getting the content (setEvents and setContent), where it creates a variable and calls a function for setting the variable (getMarkup), when the function was called, and the return statement was executed, it returns undefined. 当我创建用于获取内容的函数(setEvents和setContent)时,会在其中创建变量并调用用于设置变量的函数(getMarkup),当调用该函数并执行return语句时,它将返回未定义。 I found a thread similar, but their solution was to add the innerHTML statement DIRECTLY in the getMarkup function. 我发现了一个类似的线程,但是他们的解决方案是在getMarkup函数中直接添加innerHTML语句。 I don't want to do that. 我不想那样做。

Here's the code and the results: 这是代码和结果:

Edit : Esailija suggested that I should have just posted the code. 编辑 :Esailija建议我应该发布代码。 To me it was a tad bit easier to just take the image, but here it is: 对我来说,仅拍摄图像要容易一些,但是这里是:

function init() {
    //preloadImages();
    setEvents();
    setContent('main');
}

function setEvents() {
    var eventDiv = document.getElementById("events");
    var eventContent = getMarkup("content/events.txt");
    eventDiv.innerHTML = eventContent;
}

function setContent(which) {
    loadingScreen('start');
    var contentDiv = document.getElementById('content');
    location_ = "content/" + which + 'txt';
    //var contentContent = getMarkup('location');
    //contentDiv.innerHTML = contentContent;
    loadingScreen('stop');
}

function loadingScreen(action) {
    var loadingSpan = document.getElementById('loading');
    loadingSpan.innerHTML = "Test";
    if (action == 'start') {
        loadingSpan.innerHTML = '<p>Loading...<br><img src="images/loading.gif"></p>';
    }
    if (action == 'stop') {
        loadingSpan.innerHTML = '';
    }
}

function getMarkup(where) {
    var filerequest = new XMLHttpRequest();
    filerequest.open("GET", where, true);
    filerequest.onreadystatechange = function() {
        if (filerequest.readyState == 4 && filerequest.status == 200) {
            var test = document.getElementById("events");
            var reply = filerequest.responseText;
            //Doesn't work
            return reply;
            //Works just fine
            //test.innerHTML = reply;
        }
    };
    filerequest.send(null);
}
window.onload = init;

When I do the innerHTML instead of return it shows "Test TEST ", and when I do return instead of innerHTML, it shown "undefined". 当我执行innerHTML而不返回时,它显示“ Test TEST ”,而当我返回而不是innerHTML时,它显示“未定义”。

I really don't want to do the innerHTML part of it, so is there a workaround to make that return statement work? 我真的不想做它的innerHTML部分,那么是否有一种使该return语句起作用的解决方法?

Are you familiar with callbacks? 您熟悉回调吗? Open up Firebug and put a breakpoint on your return reply; 打开Firebug并在您的return reply;设置一个断点return reply; line - notice the call stack. 行-注意调用堆栈。 The function where you have return reply; 您有return reply;的功能return reply; is not getMarkup . 不是getMarkup

Basically you're going to have to restructure your code a little. 基本上,您将不得不稍微重组代码。 I would have getMarkup take an additional parameter - the DOM element to which you want to set its innerHTML value. 我会让getMarkup附加一个参数-您要将其innerHTML值设置为DOM元素。

It seems that you don't quite understand how ajax works. 看来您不太了解ajax的工作原理。
Once you call your getMarkup function, you send an ajax request and tell the browser to use the function after onreadystatechange to handle the reply. 调用getMarkup函数后,您将发送一个ajax请求,并告诉浏览器在onreadystatechange之后使用该函数来处理回复。 So actually when the reply is back, it's not your other functions like setContent that are calling that handler but the browser. 因此,实际上,当回复返回时,调用该处理程序的不是您的其他函数(例如setContent ,而是浏览器。 That's why the return doesn't work. 这就是为什么退货不起作用的原因。

Also when you call something like var contentContent = getMarkup('location'); 同样,当您调用类似var contentContent = getMarkup('location'); , as getMarkup has no explicit return value, so by default contentContent gets undefined . ,因为getMarkup没有显式的返回值,所以默认情况下contentContent undefined You may think that it should get the return value inside your anonymous function but that's not the case. 您可能认为它应该在您的匿名函数中获取返回值,但事实并非如此。 The getMarkup function returns immediately but the handler will be called only when the ajax response comes. getMarkup函数立即返回,但是仅当ajax响应到来时才调用处理程序。

If you want to make that nice, you will have to do something extra like: you only have one ajax handler like you did. 如果您想使它变得更好,那么您将不得不做一些额外的事情:您像以前一样只有一个ajax处理程序。 Once a function called that ajax function it register its callback into a queue and when the response is back the queue is popped and the values are then updated. 一旦一个函数调用了该ajax函数,它将把其回调函数注册到队列中,并在响应返回时弹出队列,然后更新值。 This would take some time for you to build this mechanism or you may need to check how the jQuery Ajax Queue works. 构建该机制将花费一些时间,或者您可能需要检查jQuery Ajax Queue的工作方式。

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

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