gpt4 book ai didi

javascript - XMLHttpRequest 方法的顺序很重要吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:42:59 25 4
gpt4 key购买 nike

这段代码工作正常:

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 播放器无关。订单不应该影响这一切,不是吗?

最佳答案

方法顺序对于 XMLHttpRequest 来说绝对重要。 description of open开始于:

Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.

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

来自 the examples in the WhatWG spec 的一些, onreadystatechange 应该工作,但我无法想象 setRequestHeader 会。事实上,在 open 之前调用 setRequestHeader 应该会抛出 InvalidStateError。 , it seems :

If the state is not OPENED, throw an "InvalidStateError" exception.

关于javascript - XMLHttpRequest 方法的顺序很重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com