使用JSON -headers解释XMLHttpRequest初始化中的DOM 11错误

hhh*_*hhh 5 javascript json dom xmlhttprequest

我得到这个错误,因为这更大问题的一部分在这里.

var xhr = new XMLHttpRequest();
xhr.setRequestHeader( 'Content-Type', 'application/json' );

//Error: INVALID_STATE_ERR: DOM Exception 11
Run Code Online (Sandbox Code Playgroud)

进一步研究

  1. O'Reilly的书"Javascript第6版的明确指南"(第491页)第18章"Scripted HTTP"中讨论了XMLHttpRequest,请注意,它不仅仅是关于HTTP或XML(历史文物).

  2. Mozilla关于XMLHttpREquest的开发条目在这里

Ry-*_*Ry- 6

你需要open()XMLHttpRequest,然后才能设置请求头.只需在拨打电话后将该行移至open():

var xhr = new XMLHttpRequest();
xhr.open( 'POST', 'example.php', true );
xhr.setRequestHeader( 'Content-Type', 'application/json' );
Run Code Online (Sandbox Code Playgroud)