【问题标题】:'this.response' is not printing in the console“this.response”未在控制台中打印
【发布时间】:2015-08-25 09:01:46
【问题描述】:
    function callOtherDomain() {

        var invocation = new XMLHttpRequest();
        var username = "usr";
        var password = "pass";
        var url = 'https://someurl';  
        invocation.open('GET', url, true, username,password);  
        console.log(this.responseText);                                
        invocation.send();
    }

我无法让响应适用于上述代码

【问题讨论】:

    标签: javascript http xmlhttprequest httprequest httpresponse


    【解决方案1】:

    首先,responseText 是您从XMLHttpRequest 得到的响应,所以它自然应该是invocation 的成员,而不是this

    其次,既然是请求的响应,在收到实际响应之前不会有任何东西。因此,如果请求是同步的,那么您可以在 send 调用之后进行。不幸的是,您将其作为异步请求执行,这意味着您必须创建一个响应处理程序(使用 onreadystatechange 属性)并在完全收到响应后打印响应。

    我建议您点击 onreadystatechange 属性上的链接,因为它包含一个非常简单但很好的示例,说明如何处理异步请求,完全按照您的意愿行事。

    【讨论】:

    • 应该是console.log(invocation.response)吗?
    • "第二,既然是请求的响应,那么在请求真正发出之前,不会有任何东西。"。不知道调用的背后是什么,但我们可以想象比 open 实际上返回了一个 promise。你知道这背后发生了什么吗?如果这也是一个承诺,那么您应该执行类似 invocation.open().then(function() { console.log([this, invocation].response); }) 之类的操作,具体取决于您的实现,可以调用回调定义了 this(通过调用或应用),this 将引用调用对象本身。
    • @xyzsfdc 首先,是的。但由于请求是异步,因此在请求完成之前实际上不会打印任何内容。如果您更改为使其同步,则可以在send 调用之后进行打印,否则您必须在处理函数中进行。
    • @Nico - invocation.open('GET', url, true, username,password).then(function() { console.log([this, invocation].response); }) ;不工作
    • @Nico 不,open 不返回任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2018-05-04
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多