首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript对JavaScript的响应

JavaScript对JavaScript的响应
EN

Stack Overflow用户
提问于 2016-04-03 11:49:00
回答 1查看 4.6K关注 0票数 1

我试图让JavaScript发送一些HTML作为对来自JavaScript函数的请求的响应。但是,当servlet函数被调用并且似乎正在发送响应时,Javascript函数只得到一个空字符串。

以下是Servlet方法:

代码语言:javascript
复制
String type = request.getParameter("type");
if(type.equals("locos")) {
            response.setContentType("text/html");

            //this prints out
            System.out.println("Responding with vehicle list");

            //deal with response
             PrintWriter out = response.getWriter();
             out.write("<p>test response</p>"); //finish
        }

下面是JavaScript函数:

代码语言:javascript
复制
this.updateVehicleList = function () {
        var type = "locos";

        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),true);
        xhr.send(null);

        //deal with response
        var res = xhr.responseText;

        //for testing
        if (res == "") {
            window.alert("I'm getting nothing");
        }

        view.showVehicleList(res);
    };

“我什么也得不到”的消息每次都会输出。如何让JavaScript实际接收来自Servlet的响应?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-03 11:57:12

您正在发出异步请求,因此响应无法立即可用。您正在尝试在收到响应之前获得responseText

使用onreadystatechange事件:

代码语言:javascript
复制
...
...
xhr.send(null);

xhr.onreadystatechange = function () {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
        //deal with response
        var res = xhr.responseText;

         //for testing
         if (res == "") {
            window.alert("I'm getting nothing");
         }

        view.showVehicleList(res);
    }
};

如果您打算提出同步请求,那么将第三个参数设置为false,您的原始代码就可以工作了。

代码语言:javascript
复制
xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),false);
//                                                         ^^^^^
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36385018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档