本文介紹了XMLHttpRequest 拋出 InvalidSateError 說“必須打開對象狀態";的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
代碼 -
"use strict";
var AJAX = function (params) {
this.server ={};
this.url = params.url;
this.method = params.method;
this.dataType = params.dataType;
this.formData = params.formData;
this.init = function(){
if(typeof XMLHttpRequest != 'undefined'){
this.server = new XMLHttpRequest();
this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
this.server.setRequestHeader('Content-length', this.formData.length);
this.server.setRequestHeader('Connection', 'close');
console.log("XMLHttpRequest created.");
return true;
}
};
this.send = function(){
if(this.init()){
this.server.open(this.method, this.url, true);
this.server.send(this.formData);
}
};
};
它拋出以下錯誤:
Error in event handler for contextMenus: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
如何使用 -
var data = new FormData();
data.append('user', 'sachin');
var params = {
url : 'example.com',
method : 'post',
dataType: 'json',
formData : data
};
var backgroundWindow = chrome.extension.getBackgroundPage();
var ajax = new backgroundWindow.AJAX(params);
ajax.send();
我似乎無法弄清楚背后的原因.
I can't seem to figure out what's the reason behind.
推薦答案
錯誤是直截了當的:
contextMenus 的事件處理程序出錯:InvalidStateError:無法在XMLHttpRequest"上執行setRequestHeader":對象的狀態必須是 OPENED.
Error in event handler for contextMenus: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
你需要在設置請求頭之前調用.open(..)
.
You need to call .open(..)
before setting the request headers.
鑒于您的代碼,我相信最好的方法是將調用移動到 init(..)
函數中的 open .
Given your code, I believe the best way would be to move the call to open in the init(..)
function.
var AJAX = function (params) {
this.server ={};
this.url = params.url;
this.method = params.method;
this.dataType = params.dataType;
this.formData = params.formData;
this.init = function(){
if(typeof XMLHttpRequest != 'undefined'){
this.server = new XMLHttpRequest();
//Open first, before setting the request headers.
this.server.open(this.method, this.url, true);
//Now set the request headers.
this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//this.server.setRequestHeader('Content-length', this.formData.length);
//this.server.setRequestHeader('Connection', 'close');
console.log("XMLHttpRequest created.");
return true;
}
};
this.send = function(){
if(this.init()){
this.server.send(this.formData);
}
};
};
這篇關于XMLHttpRequest 拋出 InvalidSateError 說“必須打開對象狀態";的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!