xhr.setRequestHeader报错Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED."
时间: 2024-01-16 10:03:15 浏览: 31
这个错误通常是因为在调用 `setRequestHeader()` 方法之前,没有先调用 `open()` 方法打开 XMLHttpRequest 对象。如果没有先调用 `open()` 方法,XMLHttpRequest 对象的状态是 0(UNSENT),此时不能设置请求头。
因此,可以按照以下代码顺序进行调用:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data', true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功后的处理代码
}
};
xhr.send();
```
在上面的代码中,首先调用 `open()` 方法打开 XMLHttpRequest 对象,然后再调用 `setRequestHeader()` 方法设置请求头。最后调用 `send()` 方法发送请求。
相关问题
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED. at postToTPhp
这个 error 是由于 XMLHttpRequest 对象的状态不正确导致的。在调用 XMLHttpRequest.send() 方法之前,必须先调用 XMLHttpRequest.open() 方法来打开一个请求。请确保在调用 send() 方法之前已经正确地设置了 XMLHttpRequest 对象的状态。可以使用以下代码作为模板:
```
function postToTPhp(data) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'your_url_here', true); // true 表示异步请求
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// 请求完成且响应成功
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify(data));
}
```
在这个例子中,我们使用 POST 方法请求给定的 URL,设置请求的 Content-Type 为 application/json,并将数据作为 JSON 字符串发送。当状态改变时,我们检查状态是否为 XMLHttpRequest.DONE(即 4),并且状态码为 200,这意味着请求完成且响应成功。如果这些条件为真,则我们打印响应文本。
Failed to execute 'setRequestHeader' on 'XMLHttpRequest': String contains non ISO-8859-1 code point.
这个错误提示通常表示请求头中包含了非ISO-8859-1编码的字符。XMLHttpRequest对象的setRequestHeader方法只接受ISO-8859-1编码的字符串,因此如果您在请求头中使用了其他编码的字符,就会出现这个错误。
解决这个问题的方法是将请求头中的所有字符串都转换为ISO-8859-1编码。可以使用encodeURIComponent()函数对字符串进行编码,确保其中没有非ISO-8859-1编码的字符。例如:
```
xhr.setRequestHeader("Content-Type", "application/json;charset=ISO-8859-1");
```
如果您仍然遇到问题,请提供更多上下文信息,我可以尝试帮助您解决问题。