1、项目场景:
初学Ajax时,在发送请求设置请求头中的传参格式中,我遇到这样的错误: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED
2、问题描述
3、解决方案:
这句话表示这个参数的位置不对,设置的header头必须要放到open()后面。
应该先打开服务器的连接,再设置传参格式(下面的传参格式为pplication/x-www-form-urlencoded)。
xhr.open("POST", "https://********");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
xhr.send('a=1&b=2');
补充:
post方法的第二种传参格式:
// 设置请求头中传参的格式
xhr.setRequestHeader('Content-Type','application/json')
// 将指定的参数格式放入到请求体
xhr.send( '{"a":1, "b":2}' )