4

此代码工作正常:

function callFromFlex(url, method, payload) {
   console.log("call from Flex: " + method + " " + url + " " + payload);
   var xhttp = new XMLHttpRequest();
   xhttp.open(method, url, true);
   xhttp.setRequestHeader("Content-Type", "application/json");
   xhttp.onreadystatechange = function() {
    console.log(xhttp.readyState);
       if (xhttp.readyState == 4) { 
        console.log("trying to call flash...");
           // Callback to Flash here
           ...  
       }
   };

   xhttp.send(payload);
}

但这不会 - 永远不会调用 onreadystatechange:

function callFromFlex(url, method, payload) {
    console.log("call from Flex: " + method + " " + url + " " + payload);
    var xhttp = new XMLHttpRequest();

    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
        console.log(xhttp.readyState);
        if (xhttp.readyState == 4) {    
            console.log("trying to call flash...");
            // Callback to Flash here;
            ... 
        }
    };
    xhttp.open(method, url, true);
    xhttp.send(payload);
}

我只是将 xhttp.open(method, url, true) 移动到另一个位置,并且从未调用 xhttp.onreadystatechange。检查了 Firefox 45.0.2 和 IE 11,我相信它与 Flash 播放器无关。订单不应该影响这一切,不是吗?

4

1 回答 1

4

对于 XMLHttpRequest,方法顺序是绝对重要的。的描述open开始于:

初始化一个请求。此方法将在 JavaScript 代码中使用;要从本机代码初始化请求,请改用 openRequest()。

直到open被调用,请求还没有完全初始化(分配不是初始化,这里)并且不能保证其他方法正常工作。

WhatWG 规范中的一些示例来看onreadystatechange应该可以工作,但我无法想象setRequestHeader会。事实上,调用setRequestHeader之前open应该抛出一个InvalidStateError看起来

如果状态不是 OPENED,则抛出“InvalidStateError”异常。

于 2016-05-09T16:05:30.827 回答